简体   繁体   English

如何选择INTO tableB,其名称为@tableB * FROM @tableA?

[英]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: 最后,临时结果必须存储到名称为@tableB的表中,因此在存储过程中,我尝试编写以下语句:

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( ... 创建表#tableA(...

For more information: link text 有关更多信息: 链接文本

create table #A( c1 int, c2 int ); 创建表#A(c1 int,c2 int);

insert into #A values (1,2); 插入#A值(1,2);

insert into #A values (3,4); 插入#A值(3,4);

declare @sql varchar(max); 声明@sql varchar(max);

declare @tableB sysname = '##tableB'; 声明@tableB sysname ='## tableB';

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

Print @sql; 打印@sql;

exec (@sql); exec(@sql);

go

select * from ##tableB; 从## tableB选择*;

Assuming @tableB already exists, first guess would be to try: 假设@tableB已经存在,首先要尝试的是:

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? 如果@tableB不存在,为什么它的名称需要来自用户?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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