以下のコードで非常に奇妙な動作をしました。
--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
新しいものを作成すると、既に存在すると言うため、実行が回避されることです。
常に として評価される場合、SQL がステートメントの一部をcreate table #temp (ID datetime)
実行するようにコメントを解除するのはなぜですか?true
IF
false
SQL Management Studio 11.0.2100.60 で SQL Server 2008 (10.50.2500) を実行しています。