【问题标题】:Insert multiple rows in a single query using results of a select statement使用 select 语句的结果在单个查询中插入多行
【发布时间】:2020-11-19 17:41:41
【问题描述】:

我正在寻找一种紧凑的方法来执行此操作 - 将多行插入到一个表中,其中的值来自另一个表中一行的多个列。我的目标表实际上是一个单列列表:

declare @stringList table
(
    val nvarchar(100)
)

This 是我们插入多行的方法:

INSERT INTO @stringList ( val ) VALUES
Val1, Val2, Val3, ...

这是我们从选择中插入的方式:

INSERT INTO @stringList 
SELECT col1 FROM table1 where id=something

但我似乎无法找到同时使用两者的方法。

我可以从一列中选择:

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

知道我想要的是否可行吗?

【问题讨论】:

  • 您可以使用游标从一个表中获取行级数据并通过循环插入到另一个表中。

标签: sql tsql insert sql-server-2016


【解决方案1】:

您可以使用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;

【讨论】:

  • 我的心都碎了。我不知道你可以那样使用 values 。这么多浪费的工会......
  • @DanielGimenez 。 . .这也更有效率。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-13
  • 2018-05-08
  • 1970-01-01
  • 2019-03-13
  • 2022-11-21
  • 2016-01-14
  • 2016-01-04
相关资源
最近更新 更多