我有一個很奇怪的行爲,下面的代碼。爲什麼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
你認爲錯誤是因爲'用時間碼達到這一點的表將exist'。這實際上是因爲「當你提交T-SQL(又名分析時間)表時Currently exists'。 – MatBailie
@MatBailie - 如果OP真的在運行顯示的代碼,它實際上會稍微微妙一些。在提交T-SQL時,該表不存在 - 第一個「IF」塊然後工作,然後創建一個表。發生這種情況時,批處理的其餘部分被重新編譯,如果第二個「IF」塊的內容未被註釋,則出現編譯錯誤。 –
問題是,您無法檢查表格的存在並在必要時創建它。重寫您的查詢以確保表格在IF之外的某個位置創建。如果你需要它的代碼的不同部分,只需檢查它填充的任何部分,如果需要截斷它。 –