使用 select 语句的结果在单个查询中插入多行
Insert multiple rows in a single query using results of a select statement
我正在寻找一种紧凑的方法来执行此操作 - 将多行插入到 table 中,其中的值来自另一个 table 的一行的多列。我的目的地 table 实际上是一个单列列表:
declare @stringList table
(
val nvarchar(100)
)
This 是我们如何插入多行:
INSERT INTO @stringList ( val ) VALUES
Val1, Val2, Val3, ...
这就是我们从 select 中插入的方式:
INSERT INTO @stringList
SELECT col1 FROM table1 where id=something
但我似乎找不到同时使用两者的方法。
我可以 select 从一栏:
insert into @stringList (val)
select col1 from table1 where id=something
但它不会扩展到多列:
insert into @stringList (val)
select col1, col2 from table1 where id=something
--The select list for the INSERT statement contains more items than the insert list. The number of SELECT values must match the number of INSERT columns.
我尝试了各种方法,包括使用括号,但语法不被接受:
insert into @stringList (val)
(select col1 from table1 where id=something,
select col2 from table1 where id=something
知道我想要的是否可行吗?
您可以使用 cross apply
取消透视:
insert into @stringList (val)
select v.col
from table1 t1 cross apply
(values (t1.col1), (t1.col2)) v(col)
where t1.id = something;
我正在寻找一种紧凑的方法来执行此操作 - 将多行插入到 table 中,其中的值来自另一个 table 的一行的多列。我的目的地 table 实际上是一个单列列表:
declare @stringList table
(
val nvarchar(100)
)
This 是我们如何插入多行:
INSERT INTO @stringList ( val ) VALUES
Val1, Val2, Val3, ...
这就是我们从 select 中插入的方式:
INSERT INTO @stringList
SELECT col1 FROM table1 where id=something
但我似乎找不到同时使用两者的方法。
我可以 select 从一栏:
insert into @stringList (val)
select col1 from table1 where id=something
但它不会扩展到多列:
insert into @stringList (val)
select col1, col2 from table1 where id=something
--The select list for the INSERT statement contains more items than the insert list. The number of SELECT values must match the number of INSERT columns.
我尝试了各种方法,包括使用括号,但语法不被接受:
insert into @stringList (val)
(select col1 from table1 where id=something,
select col2 from table1 where id=something
知道我想要的是否可行吗?
您可以使用 cross apply
取消透视:
insert into @stringList (val)
select v.col
from table1 t1 cross apply
(values (t1.col1), (t1.col2)) v(col)
where t1.id = something;