2

我有一个包含三个表的 DB2 数据库: locations, items, movement_history. 该items表有一个外键location_id, into locations。该movement_history表有一个外键 , item_idintoitems和两个外键, location_id_beforeand location_id_after, into locations

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

4

1 回答 1

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
于 2012-05-19T21:14:41.083 回答