简体   繁体   English

如何将多行插入到类似于“For Each”循环的 SQL 表中?

[英]How to insert multiple rows into a SQL table similar to a 'For Each' loop?

I have a table in SQL with a structure like:我在 SQL 中有一个表,其结构如下:

ID_COL ID_COL VALUE_1 VALUE_1 VALUE_2 VALUE_2 VALUE_3 VALUE_3
A一个 2 2 4 4 3 3
A一个 3 3 2 2 5 5
B 2 2 8 8 6 6
B 4 4 7 7 6 6
B 3 3 2 2 1 1
C C 7 7 9 9 6 6
... ... ... ... ... ... ... ...

For each distinct ID_COL value (A, B, C, etc.) I need to add a row.对于每个不同的ID_COL值(A、B、C 等),我需要添加一行。 Every row being inserted will have the same values for the VALUE_X columns.插入的每一行对于VALUE_X列都将具有相同的值。 For example, I'll add a row with values A, 1, 2, 3 , B, 1, 2, 3 , etc.例如,我将添加一行,其值为A, 1, 2, 3B, 1, 2, 3等。

Is there any way to do this programmatically in SQL without having to generate a bunch of separate insert statements?有没有办法在 SQL 中以编程方式执行此操作,而不必生成一堆单独的插入语句? I'm not super familiar with SQL, but in another language like Python I would do a for-each loop on the distinct ID_COL values.我对 SQL 不是很熟悉,但在另一种语言(如 Python)中,我会对不同的ID_COL值执行 for-each 循环。

If it makes a difference, this is in SQL Server.如果它有所作为,这是在 SQL Server 中。

Thanks!谢谢!

There is no need to resort to looping for this kind of thing.没有必要为这种事情求助于循环。 Your question is lacking any real details about your table or what you really want to accomplish.您的问题缺少有关您的桌子或您真正想要完成的任何真实细节。 So assuming you want the value 1, 2, 3 along with each distinct value of ID_COL it would be something like this.因此,假设您想要值 1、2、3 以及 ID_COL 的每个不同值,它将是这样的。

insert YourTable
select distinct ID_COL
    , 1
    , 2
    , 3
from YourTable

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

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