使用IF逻辑的T-SQL不能使用临时表

时间:2012-09-13 14:28:44

标签: sql-server tsql

IF OBJECT_ID('tempdb..#iftry') IS NOT NULL 
DROP TABLE #iftry

IF OBJECT_ID('BIC_Analytics.dbo.AdjudicateAllDCCharteredClaims') IS  NULL
begin
select 'this is start of first block'
 SELECT 'this is first block' as blockid
 INTO #iftry
select 'this is end of first block'
end

ELSE

begin
select 'this is start of 2nd block'
 SELECT 'this is 2nd block' as blockid
    INTO #iftry
select 'this is end of 2nd block'
end

select ':)'

select * from #iftry

继续给我错误:

Msg 2714, Level 16, State 1, Line 18
There is already an object named '#iftry' in the database.

现在可行了

IF OBJECT_ID('tempdb..#iftry') IS NOT NULL 
DROP TABLE #iftry

create table #iftry (blockid varchar(20))


IF OBJECT_ID('BIC_Analytics.dbo.AdjudicateAllDCCharteredClaims') IS NOT NULL
begin
--select 'this is start of first block'
 insert into #iftry (blockid)
 select 'this is first block' 
--select 'this is end of first block'
end

ELSE

begin
--select 'this is start of 2nd block'
 insert into #iftry (blockid)
 select 'this is 2nd block' 
--select 'this is end of 2nd block'
end

select ':)'

select * from #iftry

1 个答案:

答案 0 :(得分:4)

这是一个解析问题,而不是运行时问题。 SQL Server无法看到有两个无法访问的代码路径。

要解决此问题,请事先创建一个#temp表:

SELECT 'bogus' INTO #iftry
  WHERE 1 = 0; -- creates empty table

IF ...
  INSERT #iftry ...
ELSE ...
  INSERT #iftry ...

除非您将两个#table声明放在不同的批处理中(您实际上不能这样做),否则无法告诉SQL Server不以这种方式工作,或者构建动态SQL并使用该范围内的#temp表(不好玩)。