SQL n00b试图找出如何在不编写循环的情况下执行以下操作。
我有两张表,比如
First Second
================= ============================
Id | Name Id | FirstId | DisplayName
================= ============================
1 | 'foo'
-----------------
2 | 'bar'
----------------
3 | 'baz'
我想要一个查询在Second
中为First
中的每一行添加一行,例如
First Second
================= ============================
Id | Name Id | FirstId | DisplayName
================= ============================
1 | 'foo' 1 | 3 | 'bazness'
----------------- ----------------------------
2 | 'bar' 2 | 1 | 'fooness'
---------------- ----------------------------
3 | 'baz' 3 | 2 | 'barness'
所以公式是:对于f
中的每一行First
,在Second
中添加一行,f.Id
为FirstID
和f.Name + 'ness'
为DisplayName
。
答案 0 :(得分:2)
您只想要insert . . . select
:
insert into second (firstId, DisplayName)
select id, name + 'ness'
from first;
注意:这假定second.id
被声明为标识列。如果不是:
insert into second (id, firstId, DisplayName)
select row_number() over (order by (select null)), id, name + 'ness'
from first;