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并创建一个新的部分,它会避免运行,因为它说它已经存在。

如果它总是评估为,为什么取消注释create table #temp (ID datetime)让 SQL 运行语句的true一部分?IFfalse

我在 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 回答