下面的过程将在 SQL Server 2005 中运行正常,但在 2008 年失败了...Invalid object name 'vTemp'
Create PROCEDURE [dbo].[bulksaverecord]
as
begin
if exists (select * from sysobjects where id=object_id('vTemp'))
begin
drop view vTemp
end
declare @sql nvarchar(max)
set @sql='CREATE VIEW vTemp AS SELECT top 0 FromType,TypeID,AssessUser,
TypeTimeType,AssessTime,ItemRoleKey,UserName,SourceKey,
PartID,PartName,PositionName,ItemID,ItemName,ItemType,ItemScript,
ItemDataSourceName,ItemField,ItemKPI,ItemFun,ItemFunLimit,ItemKill,
AllKill,ItemMark,ItemPower,MarkScript,PowerScript,FromKey
FROM AssessMark'
exec sp_executesql @sql
if exists (select * from sysobjects where id=object_id('vTemp'))
begin
exec ('SELECT * FROM vTemp')
SELECT * FROM vTemp -- throws the error here
end
end
似乎在 PROCEDURE 中使用动态 sql 创建的 VIEW 将在 DYNAMIC SQL 中具有范围,即使实际上创建了 VIEW。