Check if a temporary table exists and delete if it exists before creating a temporary table

前端 未结 15 718
忘掉有多难
忘掉有多难 2020-11-29 14:13

I am using the following code to check if the temporary table exists and drop the table if it exists before creating again. It works fine as long as I don\'t change the colu

15条回答
  •  無奈伤痛
    2020-11-29 15:06

    I think the problem is you need to add GO statement in between to separate the execution into batches. As the second drop script i.e. IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results did not drop the temp table being part of single batch. Can you please try the below script.

    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
    

提交回复
热议问题