如果条件在动态 sql 内不起作用

If condition not working inside dynamic sql

在下面的动态 sql 我正在尝试检查临时 table (#Table) 是否已经存在,如果不存在则使用其他 table.

但我的问题是,无论 IF 条件中的值是多少,我总是在 If 条件

内的 select 语句中出错

There is already an object named '#Table' in the database.

下面是 sql 代码。

declare @sqlstring varchar(max)

set @sqlstring=N'

select * into #Table from mst_country


if(object_id(''tempdb..#Table'') is null)
begin

    select * into #Table from mst_country_bkp

end'

exec(@sqlstring)

谁能告诉我们为什么会发生这种情况?

完成查询后,您需要删除临时文件 table:

declare @sqlstring varchar(max)

set @sqlstring=N'
IF OBJECT_ID(''tempdb.dbo.#Table'', ''U'') IS NOT NULL
DROP TABLE #Table;  

select * into #Table from mst_country


if(object_id(''tempdb..#Table'') is null)
begin  
    select * into #Table from mst_country_bkp    
end'

exec(@sqlstring)

编辑:

问题是在同一个 sql 语句中不能有两个 SELECT INTO。 This is a leftover from SQL 6.5 which did not have deferred name resolution.试试这个:

declare @sqlstring varchar(max)

set @sqlstring=N'
IF OBJECT_ID(''tempdb.dbo.#Table'', ''U'') IS NOT NULL
DROP TABLE #Table;  

select * into #Table from mst_country

insert into #Table(col1,col2,....)
select col1,col2,.... from mst_country_bkp    
end'

exec(@sqlstring)

编译 sqlserver 时不允许您在同一范围内创建相同的临时 table 两次。你实际上可以像这样欺骗 sqlserver,所以它不会意识到临时 table 已经创建:

declare @sqlstring varchar(max)

set @sqlstring=N'

exec(''select * into #Table from mst_country'')


if(object_id(''tempdb..#Table'') is null)
    select * into #Table from mst_country_bkp
'

exec(@sqlstring)