如何将指定的一组列的所有行从1个表插入到另一个表中

时间:2017-02-06 19:27:33

标签: sql sql-server tsql

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.IdFirstIDf.Name + 'ness'DisplayName

1 个答案:

答案 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;