4

以下のコードで非常に奇妙な動作をしました。

--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)実行するようにコメントを解除するのはなぜですか?trueIFfalse

SQL Management Studio 11.0.2100.60 で SQL Server 2008 (10.50.2500) を実行しています。

4

2 に答える 2

4

エラーは解析時、つまりクエリが実際に実行される前に発生します。これを置き換えます:

create table #temp (ID datetime) 

と:

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

execは新しいスコープを作成するためcreate table、一時テーブルが存在しない場合にのみ解析されます。

于 2013-07-15T12:38:01.533 に答える
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
于 2013-07-15T12:38:13.533 に答える