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

前端 未结 15 733
忘掉有多难
忘掉有多难 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 14:56

    Instead of dropping and re-creating the temp table you can truncate and reuse it

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

    If you are using Sql Server 2016 or Azure Sql Database then use the below syntax to drop the temp table and recreate it. More info here 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,
      )
    

提交回复
热议问题