Temporary table in SQL server causing ' There is already an object named' error

前端 未结 5 1053
难免孤独
难免孤独 2021-02-02 05:10

I have the following issue in SQL Server, I have some code that looks like this:

DROP TABLE #TMPGUARDIAN
CREATE TABLE #TMPGUARDIAN(
LAST_NAME NVARCHAR(30),
FRST_         


        
5条回答
  •  孤城傲影
    2021-02-02 05:49

    You must modify the query like this

    CREATE TABLE #TMPGUARDIAN(
    LAST_NAME NVARCHAR(30),
    FRST_NAME NVARCHAR(30))  
    
    INSERT INTO #TMPGUARDIAN(FRST_NAME,LAST_NAME)
    SELECT LAST_NAME,FRST_NAME  FROM TBL_PEOPLE
    

    -- Make a last session for clearing the all temporary tables. always drop at end. In your case, sometimes, there might be an error happen if the table is not exists, while you trying to delete.

    DROP TABLE #TMPGUARDIAN
    

    Avoid using insert into Because If you are using insert into then in future if you want to modify the temp table by adding a new column which can be filled after some process (not along with insert). At that time, you need to rework and design it in the same manner.

    Use Table Variable http://odetocode.com/articles/365.aspx

    declare @userData TABLE(
     LAST_NAME NVARCHAR(30),
        FRST_NAME NVARCHAR(30)
    )
    

    Advantages No need for Drop statements, since this will be similar to variables. Scope ends immediately after the execution.

提交回复
热议问题