0

下面的过程将在 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。

4

3 回答 3

1

这个测试脚本对我重复工作:

if object_id('TestProc') is not null
    drop procedure TestProc
if object_id('TestView') is not null
    drop view TestView
go
create proc TestProc
as
exec ('create view TestView as select 1 as a')
select * from TestView
go
exec TestProc

就像 Gordon Linoff 回答的那样,仔细检查您的视图定义?

于 2013-03-25T19:34:59.753 回答
1

当我将视图定义修改为:

select * from information_schema.tables

我怀疑您的视图定义有问题。

于 2013-03-25T19:35:47.043 回答
0

谢谢!我找到了原因。

我改:create view 创建dbo.view,问题就没有了。所以

于 2013-03-26T08:27:21.960 回答