【发布时间】:2016-05-11 04:45:52
【问题描述】:
我在 SO 中进行了搜索,但找不到任何适合我的目的。我只需要将唯一行从一个表插入到另一个表中。我有:
table1
id name bookid bookname start_date end_date rel_date rel_id
1 horror 1221 rockys 04/01/2016 04/30/2016 05/01/2016 4545
2 horror 1331 elm 04/01/2016 04/30/2016 05/01/2016 5656
table2
id name bookid bookname start_date end_date rel_date rel_id
1 horror 1221 rockys 04/01/2016 04/30/2016 05/01/2016 4545
2 horror 1441 elm 04/01/2016 04/30/2016 05/01/2016 5656
我需要将 table2 中 id = 2 的行插入到 table1 中,并从 table1 中删除 id = 2 的行,因为即使其余列匹配,bookid 也是不同的。 我尝试了以下操作:
insert into table1
select * from table2
where not exists (select * from table2 where table1.id = table2.id
and table1.name = table2.name and table1.bookid = table2.bookid and
table1.bookname = table2.bookname and table1.start_date = table2.start_date
and table1.end_date = table2.end_date and table1.rel_date = table2.rel_date
and table1.rel_id = table2.rel_id)
有什么方法可以在一个 sql 块中完成所有这些操作?
【问题讨论】:
-
使用连接先删除后插入
-
再想一想,如果只是 bookid 的问题,为什么不能用 join 编写更新查询?
-
您还可以查看 TSQL 中的
MERGE命令。 -
@techspider -- 在这种情况下,它只是 bookid,它可以是任何/所有剩余的列。我没有识别列,因为这是 ssis 包内的 sql 任务。 - 马特
-
在您确定两个表中都匹配的标识列之前,您无法正确执行此操作
标签: sql-server tsql