在SQL中将行从一个表复制到另一个表

时间:2014-09-13 17:07:58

标签: sql

我有两个数据库 - db1和db2如下:

db1..Model

ModelId ModelName
0       BMW

db1..Category

CategoryId  CategoryName
0           Undercarriage
1           Engine

db1..ItemList

ModelId CategoryId      DataId  Name
0       0               1       cap
0       0               2       cushion
0       0               3       spacer
0       1               1       cushion

然后我将db1中的Model和Category复制到db2:

db2..Model

Id  ModelName
1   BMW

db2..Category

Id  CategoryName
1   Undercarriage
2   Engine

如何将记录写入 db2..Item ,以便行如下所示:

Id  ModelId     CategoryId  DataId  Name
1   1           1           1       cap
2   1           1           2       cushion
3   1           1           3       spacer
4   1           2           1       cushion 

1 个答案:

答案 0 :(得分:1)

假设db1和db2在同一台服务器上,这样的东西应该可以工作:

INSERT INTO db2.dbo.Item (ModelId, CategoryId, DataId, Name)
SELECT
    (
        SELECT Model.Id
        FROM db2.dbo.Model
        WHERE db2.dbo.Model.ModelName = (
            SELECT Model.ModelName
            FROM db1.dbo.Model
            WHERE Model.ModelId = ItemList.ModelId
        )
    )
    (
        SELECT Category.Id
        FROM db2.dbo.Category
        WHERE db2.dbo.Category.CategoryName = (
            SELECT Category.CategoryName
            FROM db1.dbo.Category
            WHERE Category.CategoryId = ItemList.CategoryId
        )
    )
    DataId,
    Name
FROM db1.dbo.ItemList