2012-09-13 19 views
3
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 

不斷給我的錯誤:T-SQL與IF邏輯不與臨時表的工作

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 

回答

4

這是一個分析問題,而不是運行問題。 SQL Server無法看到有兩個代碼路徑無法到達。

要解決它,創建#temp表一次達陣:

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

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

有沒有辦法告訴SQL Server不要,除非你把兩個#table聲明分批以這種方式工作(其中你不能這麼做),或者構建動態SQL,並在該範圍內使用#temp表(不好玩)。

+0

現在感謝它的工作:)我應該在哪裏發佈我的答案查詢? – venky80