[英]How to insert all the rows of a specified set of columns from 1 table into another
SQL n00b trying to figure out how to do the following without writing a loop. SQL n00b试图弄清楚如何执行以下操作而不编写循环。
I have 2 tables like 我有2张桌子
First Second
================= ============================
Id | Name Id | FirstId | DisplayName
================= ============================
1 | 'foo'
-----------------
2 | 'bar'
----------------
3 | 'baz'
and I want a query that places a row in Second
for every row in First
, like 我想要一个查询,在First
每一行都在Second
放置一行,例如
First Second
================= ============================
Id | Name Id | FirstId | DisplayName
================= ============================
1 | 'foo' 1 | 3 | 'bazness'
----------------- ----------------------------
2 | 'bar' 2 | 1 | 'fooness'
---------------- ----------------------------
3 | 'baz' 3 | 2 | 'barness'
So the formula was: for each row f
in First
, add a row in Second
with f.Id
as FirstID
and f.Name + 'ness'
as DisplayName
. 因此公式为:对于First
每行f
,在Second
添加一行,其中f.Id
为FirstID
, f.Name + 'ness'
为DisplayName
。
You just want insert . . . select
您只想insert . . . select
insert . . . select
insert . . . select
: insert . . . select
:
insert into second (firstId, DisplayName)
select id, name + 'ness'
from first;
Note: This assumes that second.id
is declared as an identity column. 注意:这假定将second.id
声明为标识列。 If not: 如果不:
insert into second (id, firstId, DisplayName)
select row_number() over (order by (select null)), id, name + 'ness'
from first;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.