2013-07-15 30 views
4

我有一個很奇怪的行爲,下面的代碼。爲什麼SQL會拋出一個錯誤,如果我有一個合法的代碼永遠不會到達?

--IMPORTANT: Do not use 'GO' since it will terminate 
--the batch and it is only usable in Microsoft tools 
--and not in the code itself. 
--I don't really need a workaround I want to know why 
--this behavior happens. 

--Create the first time if doesn't exists 

IF OBJECT_ID('tempdb.dbo.#temp') IS NULL 
    begin 
     create table #temp (ID datetime)   
    end 


--I've just created so it should evaluates as False 
IF OBJECT_ID('tempdb.dbo.#temp') IS NULL 
    begin 
     print 'does not exists' 
     --uncomment the below line and you will see 
     --an error saying table already exists 
     --even though the IF was evaluate as TRUE 

     --create table #temp (ID datetime)  
    end 
else 
    begin 
     print 'exists' 
    end 

我試圖實現更復雜的腳本,但我最終有一個問題,以驗證是否臨時表存在並在必要時創建它。

在我的代碼的一部分,我可以有或沒有創建一個臨時表。所以我檢查它是否存在,如果不存在,我想創建它。

問題是,如果我只打印它評估爲exists的消息,但是如果我取消註釋其中的部分does not exists並創建一個新的它可以避免運行,因爲它說它已經存在。

爲什麼取消註釋create table #temp (ID datetime)使SQL運行IF聲明true一部分,如果它總是作爲計算false

我運行SQL Server 2008(10.50.2500)在SQL Management Studio中11.0.2100.60

+0

你認爲錯誤是因爲'用時間碼達到這一點的表將exist'。這實際上是因爲「當你提交T-SQL(又名分析時間)表時Currently exists'。 – MatBailie

+0

@MatBailie - 如果OP真的在運行顯示的代碼,它實際上會稍微微妙一些。在提交T-SQL時,該表不存在 - 第一個「IF」塊然後工作,然後創建一個表。發生這種情況時,批處理的其餘部分被重新編譯,如果第二個「IF」塊的內容未被註釋,則出現編譯錯誤。 –

+0

問題是,您無法檢查表格的存在並在必要時創建它。重寫您的查詢以確保表格在IF之外的某個位置創建。如果你需要它的代碼的不同部分,只需檢查它填充的任何部分,如果需要截斷它。 –

回答

4

試試這個方法:

IF OBJECT_ID('#temp') IS NOT NULL 
    begin 
     exec('drop table #temp ')   
    end 
go 
create table tempdb..#temp (ID datetime) 

IF OBJECT_ID('#temp') IS NULL 
    begin 
     select 'does not exists' 

    end 
else 
    begin 
     select 'exists' 
    end 

IF OBJECT_ID('tempdb.dbo.#temp') IS NULL 
    begin 
     exec('create table #temp (ID datetime)')   
    end 




--I've just created so it should evaluates as False 
IF OBJECT_ID('tempdb.dbo.#temp') IS NULL 
    begin 
     print 'does not exists' 
     --uncomment the below line and you will see 
     --an error saying table already exists 
     --even though the IF was evaluate as TRUE 

     --create table #temp (ID datetime)  
    end 
else 
    begin 
     print 'exists' 
    end 
+0

如果在動態sql中創建#temp表,它將只存在於相同的動態sql中。所以第二個IF將永遠是'不存在' –

+0

不,在您的會話期間存在表格。我已經從你的狀態中刪除了'tempdb.dbo.',也許它會起作用。 – Parado

+1

請嘗試:http://sqlfiddle.com/#!6/d41d8/5562或http://sqlfiddle.com/#!6/d41d8/5563 –

4

你的錯誤發生在解析時間,也就是說,實際執行查詢之前。

create table #temp (ID datetime) 

有::替換此

exec('create table #temp (ID datetime)') 

由於exec創建一個新的範圍,當臨時表不存在create table只解析。

相關問題