寻找SQL查询来执行以下操作:
x
的{{1}}列的所有值插入table1
的列y
,如果
表2中不存在它们table2
的值不再存在,则table2
删除记录
y
x
列
醇>
我尝试插入或忽略插入查询而在sql server 2008 R2中没有运气
答案 0 :(得分:3)
听起来非常适合SQL Server MERGE
;
MERGE table2 AS t2
USING table1 AS t1
ON (t2.y = t1.x)
WHEN NOT MATCHED BY TARGET
THEN INSERT (y) VALUES(t1.x)
WHEN NOT MATCHED BY SOURCE
THEN DELETE;
答案 1 :(得分:2)
这会将Table1,colX中的所有记录插入Table2,colY:
INSERT INTO Table2 (ColY)
SELECT ColX
FROM Table1
WHERE ColX NOT IN (SELECT ColY FROM Table2)
您无法删除列中的所有记录。但是,您可以将它们设置为NULL,或者如果要删除行,也可以执行此操作。请告诉我们。
DELETE FROM Table2
WHERE ColY NOT IN (SELECT ColX From Table1)
OR
UPDATE Table2
SET ColY = NULL
WHERE ColY NOT IN (SELECT ColX From Table1)
祝你好运。
答案 2 :(得分:1)
您可以使用Merge Statement
MERGE table2 AS t2
USING table1 AS t1
ON (t2.y = t1.x)
WHEN NOT MATCHED BY TARGET
THEN INSERT(y) VALUES(t1.x)
WHEN NOT MATCHED BY SOURCE
THEN DELETE
OUTPUT $action, inserted.*, deleted.*;