如果没有外部引用则删除行,否则更新

时间:2012-05-09 14:05:58

标签: sql sql-update db2 delete-row

我有一个包含三个表的DB2数据库:locationsitemsmovement_historyitems表的外键location_idlocationsmovement_history表在[{1}}中有一个外键item_id,在items中有两个外键location_id_beforelocation_id_after。< / p>

如果locationslocation中没有行引用,我想删除items。如果在某处引用了movement_history ,我只想更新它以标记为已删除。有没有办法在一个声明中这样做?最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

尝试这样的命令:

MERGE INTO LOCATIONS AS LOC
USING (
  SELECT Q1.ID, COALESCE(Q4.LOCATION_AFTER, Q3.LOCATION_BEFORE, Q2.LOCATION) AS ANY_REF
  FROM LOCATIONS Q1
    LEFT OUTER JOIN ITEMS Q2 ON Q2.LOCATION = Q1.ID
    LEFT OUTER JOIN MOVEMENT_HISTORY Q3 ON Q3.LOCATION_BEFORE = Q1.ID
    LEFT OUTER JOIN MOVEMENT_HISTORY Q4 ON Q4.LOCATION_AFTER = Q1.ID) AS T1
    ON LOC.ID = T1.ID
WHEN MATCHED AND T1.ANY_REF IS NOT NULL THEN
  UPDATE SET ACTUAL = 'N'
WHEN MATCHED AND T1.ANY_REF IS NULL THEN
  DELETE