在 Insert into from an existing table 中使用列名作为参数

Use column names as parameter in Insert into from an existing table

我想将数据从一个 table 复制到另一个现有 table。为此,我使用以下查询:

insert into table_A(col1, col2, .....)
select col1, col2, .....
from table_B

但是,我希望这些列列表来自现有的 table 或视图。 table 包含一个包含所有列名称的列 col_name

我想要下面给出的东西:

insert into table_A(select col_name from y)
select (select col_name from y)
from table_B

您要求的是动态的SQL:即构建一个查询字符串,然后执行它。假设你的 SQL 服务器版本支持 string_agg():

declare @lst nvarchar(max), @sql nvarchar(max);
select @lst = string_agg(col_name, ', ') within group(order by col_name) from y;
set @sql = N'insert into table_a (' + @lst + N') select ' + @lst + N' from table_b';
EXEC sp_executesql @sql;

Demo on DB Fiddle:

create table table_a(id int, val int);
create table table_b(id int, val int);
create table y(col_name varchar(10));

insert into y values('id'), ('val');
insert into table_b values(1, 2), (3, 4);

declare @lst nvarchar(max), @sql nvarchar(max);
select @lst = string_agg(col_name, ', ') within group(order by col_name) from y;
set @sql = N'insert into table_a (' + @lst + N') select ' + @lst + N' from table_b';
EXEC sp_executesql @sql;

select * from table_b;
id | val
-: | --:
 1 |   2
 3 |   4