如果存在则删除sql如果两个表之间不存在则删除

时间:2013-02-05 18:21:30

标签: sql sql-server sql-server-2008 sql-server-2008-r2

寻找SQL查询来执行以下操作:

  1. x的{​​{1}}列的所有值插入table1的列y,如果 表2中不存在它们
  2. 如果clumn table2的值不再存在,则
  3. 从列table2删除记录 y
  4. x

    我尝试插入或忽略插入查询而在sql server 2008 R2中没有运气

3 个答案:

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

An SQLfiddle to test with

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