简体   繁体   中英

How to SELECT INTO tableB which name is @tableB * FROM @tableA?

I am creating a stored procedure which has to create a table which name depends on input variable. For temporary results I have declared a table variable:

declare @tableA TABLE(
column1,
column2,
..
)

The output table name depends on the user's input so I have declared another variable

declare @tableB varchar = ...

In the end the temporary results have to be stored into table which name is @tableB so in the stored procedure I have tried to write the following statement:

declare @sql varchar(max)
set @sql = 'SELECT * INTO ' + @tableB + ' FROM @tableA'
exec(@sql)

which is not correct. Does anyone know how to insert values from table variable into table which name is variable?

You can't use table variables here, try to use temporary tables. create table #tableA( ...

For more information: link text

create table #A( c1 int, c2 int );

insert into #A values (1,2);

insert into #A values (3,4);

declare @sql varchar(max);

declare @tableB sysname = '##tableB';

set @sql = 'SELECT * INTO ' + @tableB + ' FROM #A';

Print @sql;

exec (@sql);

go

select * from ##tableB;

Assuming @tableB already exists, first guess would be to try:

SET @sql =
    'INSERT
    (
        col1,
        col2
    )
    INTO ' + @tableB + ' 
    SELECT 
    (
        col1, 
        col2
    )
    FROM
        @tableA'

This isn't syntax-checked, so watch out!

If @tableB doesn't exist, why does its name need to come from the user?

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