首页 文章

检查临时表是否存在,如果存在,则在创建临时表之前删除它

提问于
浏览
536

我使用以下代码检查临时表是否存在,如果存在,则在再次创建之前删除该表 . 只要我不更改列,它就可以正常工作 . 如果我稍后添加一个列,则会显示“无效列”的错误 . 请让我知道我做错了什么 .

IF OBJECT_ID('tempdb..#Results') IS NOT NULL
    DROP TABLE #Results

CREATE TABLE #Results
(
    Company                CHAR(3),
    StepId                TINYINT,
    FieldId                TINYINT,
)

select company, stepid, fieldid from #Results

--Works fine to this point

IF OBJECT_ID('tempdb..#Results') IS NOT NULL
    DROP TABLE #Results

CREATE TABLE #Results
(
    Company                CHAR(3),
    StepId                TINYINT,
    FieldId                TINYINT,
    NewColumn            NVARCHAR(50)
)

select company, stepid, fieldid, NewColumn from #Results

--Does not work

13 回答

  • 604

    我无法重现错误 .

    也许我不理解这个问题 .

    以下在SQL Server 2005中对我来说很好,在第二个选择结果中出现了额外的“foo”列:

    IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
    GO
    CREATE TABLE #Results ( Company CHAR(3), StepId TINYINT, FieldId TINYINT )
    GO
    select company, stepid, fieldid from #Results
    GO
    ALTER TABLE #Results ADD foo VARCHAR(50) NULL
    GO
    select company, stepid, fieldid, foo from #Results
    GO
    IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
    GO
    
  • -7

    声明应该是顺序

    • 表的Alter语句

    • GO

    • 选择语句 .

    如果没有'GO',整个事物将被视为一个单独的脚本,当select语句查找列时,将无法找到它 .

    使用“GO”,它会将脚本的一部分视为“GO”作为一个批处理,并在“GO”之后进入查询之前执行 .

  • 0

    而不是 dropping 并重新创建临时表,您可以 truncate 并重复使用它

    IF OBJECT_ID('tempdb..#Results') IS NOT NULL
        Truncate TABLE #Results
    else
        CREATE TABLE #Results
        (
            Company             CHAR(3),
            StepId              TINYINT,
            FieldId             TINYINT,
        )
    

    如果您使用 Sql Server 2016Azure Sql Database ,则使用以下语法删除临时表并重新创建它 . 更多信息在这里MSDN

    Syntax

    DROP TABLE [IF EXISTS] [database_name . [schema_name] . | schema_name . ] table_name [,... n]

    Query:

    DROP TABLE IF EXISTS tempdb.dbo.#Results
    CREATE TABLE #Results
      (
       Company             CHAR(3),
       StepId              TINYINT,
       FieldId             TINYINT,
      )
    
  • 3

    我认为问题是您需要在两者之间添加GO语句以将执行分成批处理 . 由于第二个删除脚本,即 IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results 没有删除临时表是单个批处理的一部分 . 你能试试下面的剧本吗?

    IF OBJECT_ID('tempdb..#Results') IS NOT NULL
        DROP TABLE #Results
    
    CREATE TABLE #Results
    (
        Company                CHAR(3),
        StepId                TINYINT,
        FieldId                TINYINT,
    )
    
    GO
    
    select company, stepid, fieldid from #Results
    
    IF OBJECT_ID('tempdb..#Results') IS NOT NULL
    DROP TABLE #Results
    
    CREATE TABLE #Results
    (
        Company                CHAR(3),
        StepId                TINYINT,
        FieldId                TINYINT,
        NewColumn            NVARCHAR(50)
    )
    
    GO
    
    select company, stepid, fieldid, NewColumn from #Results
    
  • 15

    这对我有用:social.msdn.microsoft.com/Forums/en/transactsql/thread/02c6da90-954d-487d-a823-e24b891ec1b0?prof=required

    if exists (
        select  * from tempdb.dbo.sysobjects o
        where o.xtype in ('U') 
    
       and o.id = object_id(N'tempdb..#tempTable')
    )
    DROP TABLE #tempTable;
    
  • 10

    OBJECT_ID 以来,我身边的一点评论对我不起作用 . 它总是会返回

    `#tempTable不存在

    ..尽管它存在 does . 我发现它存储了不同的名称(后缀为 _ 下划线),如下所示:

    #tempTable________

    这适合我:

    IF EXISTS(SELECT [name] FROM tempdb.sys.tables WHERE [name] like '#tempTable%') BEGIN
       DROP TABLE #tempTable;
    END;
    
  • 5

    pmac72正在使用GO将查询分解为批处理并使用ALTER .

    您似乎正在运行相同的批处理,但在更改后运行它两次:DROP ... CREATE ... edit ... DROP ... CREATE ..

    也许发布您的 exact 代码,以便我们可以看到发生了什么 .

  • 38

    我已经创建临时表时通常会遇到此错误;检查SQL语句是否有错误的代码会看到“旧”临时表,并返回后续语句中列数的错误计数,就好像临时表从未被删除一样 .

    在创建具有较少列的版本后更改临时表中的列数后,删除表,然后运行查询 .

  • 27

    我最近看到DBA做了类似的事情:

    begin try
        drop table #temp
    end try
    
    begin catch 
        print 'table does not exist'
    end catch 
    
    create table #temp(a int, b int)
    
  • 4

    我的代码使用了一个更改的 Source 表,以及一个必须与这些更改匹配的 Destination 表 .

    -- 
    -- Sample SQL to update only rows in a "Destination" Table
    --  based on only rows that have changed in a "Source" table
    --
    
    
    --
    -- Drop and Create a Temp Table to use as the "Source" Table
    --
    IF OBJECT_ID('tempdb..#tSource') IS NOT NULL drop table #tSource
    create table #tSource (Col1 int, Col2 int, Col3 int, Col4 int)
    
    --
    -- Insert some values into the source
    --
    Insert #tSource (Col1, Col2, Col3, Col4) Values(1,1,1,1)
    Insert #tSource (Col1, Col2, Col3, Col4) Values(2,1,1,2)
    Insert #tSource (Col1, Col2, Col3, Col4) Values(3,1,1,3)
    Insert #tSource (Col1, Col2, Col3, Col4) Values(4,1,1,4)
    Insert #tSource (Col1, Col2, Col3, Col4) Values(5,1,1,5)
    Insert #tSource (Col1, Col2, Col3, Col4) Values(6,1,1,6)
    
    --
    -- Drop and Create a Temp Table to use as the "Destination" Table
    --
    IF OBJECT_ID('tempdb..#tDest') IS NOT NULL drop Table #tDest
    create table #tDest (Col1 int, Col2 int, Col3 int, Col4 int)
    
    --
    -- Add all Rows from the Source to the Destination
    --
    Insert #tDest
    Select Col1, Col2, Col3, Col4 from #tSource
    
    
    --
    -- Look at both tables to see that they are the same
    --
    select *
    from #tSource
    Select *
    from #tDest
    
    --
    -- Make some changes to the Source
    --
    update #tSource
        Set Col3=19
        Where Col1=1
    update #tSource
        Set Col3=29
        Where Col1=2
    update #tSource
        Set Col2=38
        Where Col1=3
    update #tSource
        Set Col2=48
        Where Col1=4
    
    --
    -- Look at the Differences
    -- Note: Only 4 rows are different. 2 Rows have remained the same.
    --
    Select Col1, Col2, Col3, Col4
    from #tSource
    except
    Select Col1, Col2, Col3, Col4
    from #tDest
    
    --
    -- Update only the rows that have changed
    -- Note: I am using Col1 like an ID column
    --
    Update #tDest
        Set Col2=S.Col2,
            Col3=S.Col3,
            Col4=S.Col4
    From    (   Select Col1, Col2, Col3, Col4
                from #tSource
                except
                Select Col1, Col2, Col3, Col4
                from #tDest
            ) S
    Where #tDest.Col1=S.Col1 
    
    --
    -- Look at the tables again to see that
    --  the destination table has changed to match
    --  the source table.
    
    select *
    from #tSource
    Select *
    from #tDest
    
    --
    -- Clean Up
    --
    drop table #tSource
    drop table #tDest
    
  • 1

    现在,如果您使用的是新版本的SSMS,则可以使用以下语法

    DROP TABLE IF EXISTS schema.yourtable(even temporary tables #...)
    
  • 61

    是的,“无效列”此错误来自“select company,stepid,fieldid,NewColumn from #Results”行 .

    运行t-sql有两个阶段,

    首先,解析,在这个阶段,sql server检查你提交的sql字符串的更正,包括表的列,并优化你的查询以获得最快的retreival .

    第二,运行,检索数据 .

    如果表#Results存在,那么解析过程将检查您指定的列是否有效,否则(表不存在)解析将通过您指定的检查列传递 .

  • 39
    CREATE TABLE #tempTable (id int IDENTITY(1, 1) PRIMARY KEY, name nvarchar(500), value nvarchar(500))    
    
    BEGIN TRY
        DELETE FROM #tempTable
    
        PRINT 'Table deleted'
    
    END TRY
    
    BEGIN CATCH
        PRINT 'Table does not exist'
    
    END CATCH
    

相关问题