简体   繁体   English

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

[英]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.IdFirstIDf.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.

相关问题 从表中选择设置了其他所有列的表中的行 - Select rows from table where all columns in another are set 如何使用存储过程更新另一个表中的所有列和行 - How to update all columns and rows from another table with a stored procedure SQL将一个表中的多行插入另一个表的列中 - SQL insert multiple rows from one table into columns on another table 从1个表中选择多个列插入另一个表的多行 - select mutiple columns from 1 table insert into multiple rows of another table 将一个表中的行插入到具有特定模式的另一个表的列中 - Insert rows from one table to columns of another table with specific pattern 当一个(或多个)列的值需要从另一个表派生时,如何将多行插入到 SQL 表中? - How to insert multiple rows into an SQL table when the values for one (or more) of the columns need to be derived from another table? 将数据库中一个表中的特定行插入到具有不同列的另一个表中 - Insert specific rows from one table in database into another with different columns SQL,如何将表的所有行插入另一行 - SQL, how to insert all rows of a table into another one 如何输出表中所有行的指定百分比? - How to output a specified percent of all rows from a table? 我想以行的形式将一个表的所有列数据插入到另一个表中 - I want to insert all columns data of an table in to another table in form of rows
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM