简体   繁体   English

SQL每行一次插入到表2列

[英]SQL Insert to table 2 column at a time on each row

I am stuck on a problem where I need to insert data into a another table, but in a way that I insert 2 columns, then stay on the same row, insert the next 2 and so on. 我陷入了一个需要在另一个表中插入数据的问题,但是我插入了两列,然后停留在同一行,然后插入下两列,依此类推。

I have the following table data 我有以下表格数据

在此处输入图片说明

I have a table with 2 columns I want to fill but want data to be entered like: 我有一个要填充两列的表格,但想要输入数据,例如:

Row 1:(Row1A,Row1B)
Row 2:(Row1C,Row1D)
Row 3:(Row1E,Row1D)
Row 4:(Row2A,Row2B)
Row 5:(Row2C,Row2D)
Row 6:(Row2E,Row2F)

I can achieve the above using a loop, however I want to know another way that can improve performance. 我可以使用循环来实现上述目的,但是我想知道另一种可以提高性能的方法。 Is there a way to achieve this? 有没有办法做到这一点?

Edit: Order needs to be correct. 编辑:订单需要正确。 I will need the first row columns added to the table first before moving onto second row. 我需要先将第一行列添加到表中,然后再移至第二行。

I would use apply : 我会用apply

insert into t2(col1, col2)
    select col1, col2
    from data d cross apply
         (values (varchar1, varchar2), (varchar3, varchar4), (varchar5, varchar6)
         ) v(col1, col2);

Tables represent unordered sets. 表格代表无序集。 Because you have exactly two columns, you don't have a column to specify the ordering. 因为您只有两列,所以没有一列可以指定顺序。 If you did, then an order by would allow you to have an identity column that captures the ordering. 如果您这样做了,那么order by将允许您拥有一个identity列来捕获订单。 This would look like: 看起来像:

insert into t2(col1, col2)
    select col1, col2
    from data d cross apply
         (values (varchar1, varchar2, 1), (varchar3, varchar4, 2), (varchar5, varchar6, 3)
         ) v(col1, col2, priority)
    order by d.id, v.priority;

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

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