简体   繁体   中英

Use two insert into statements in a stored procedure

I tried to use two insert into statements in one stored procedure like this:

CREATE PROCEDURE dbo.test
  
AS
BEGIN
    DROP TABLE IF EXISTS #temp;

    SELECT *
    INTO #temp
    FROM sys.column_master_keys AS CMK;

    -- some statement
    -- some statement
    -- some statement

    DROP TABLE IF EXISTS #temp;

    SELECT *
    INTO #temp
    FROM INFORMATION_SCHEMA.COLUMNS AS C;
END;

Error message:

There is already an object named '#temp' in the database.

How to use one temporary table for many insert into in one stored procedure?

This is occurring because the code is compiled before it is run. During the compilation phase, SQL Server sees the two INSERT statements that create the table. It does not execute them, because it is only devising the execution plans.

Because the code is not being executed, the compilation phase misses the DROP TABLE . Alas. It sees that the table already exists when the second is executed, generating the error.

In any case, this is very easily fixed by giving the tables different names.

You can use one temporary table for many insert into statements in one stored procedure.
To make it happen you have to use dynamic SQL.

CREATE PROCEDURE dbo.test
  
AS
BEGIN
    DROP TABLE IF EXISTS #temp;

    EXEC('SELECT *
    INTO #temp
    FROM sys.column_master_keys AS CMK;')

    -- some statement
    -- some statement
    -- some statement

    DROP TABLE IF EXISTS #temp;

    EXEC('SELECT *
    INTO #temp
    FROM INFORMATION_SCHEMA.COLUMNS AS C;')
END;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM