2016-11-16 71 views
-2

我有一個表,其中Deleted標記(bit)列。如何才能實現它?表中的已刪除標記

在此列以下條件:

  • 如果記錄是新的或更新,設置爲1

  • 如果從源中刪除,設置爲0

我想可以在合併聲明中做出。但我不知道該怎麼做。或者也許有另一種方式?

+0

這麼簡單'DELETE YourTable WHERE FlagColumn = 1'? (我實際上不知道你是如何設置1或0 ...)根據你的編輯,它應該是'WHERE FlagColumn = 0' ... **請注意真實數據!!! ** – Shnugo

回答

0

我想你可以使用一個MERGE語句來做到這一點:

merge into myTable using SourceTable 
on myTable.pk = sourcetable.pk  
when matched then update set 
/*add any update columns here*/ 
Deleted = 0  
when not matched by target then insert 
(pk, abcd, deleted) 
values 
(pk, xyz, 0) 
when not matched by source then update set Deleted = 1 

這將插入不存在到目標表中的所有行。這將更新目標相匹配的任何行和任何行,但不是源將有標誌更新爲1

+0

謝謝,夥計們! –

0

您可能要仔細檢查你的要求,因爲對於一個Deleted標誌的規範將是0不刪除和1已刪除。 0是錯誤的,並且1爲真。事實上,這很常見,我只是假設這就是你想要的。

至於有MERGE設置它,你會想要做的事,如:

MERGE MyTable as Target 
USING YourTable as Source ON 
    Target.Id = Source.Id 
WHEN MATCHED THEN 
    --Exists in both Source and Target 
    UPDATE SET Deleted = 0 /* include other columns to update here */ 
WHEN NOT MATCHED BY Source THEN 
    --Source was deleted 
    UPDATE SET Deleted = 1 
WHEN NOT MATCHED BY Target THEN 
    --Source was added 
    INSERT (Id, Deleted /* include other columns to insert here */) 
    VALUES (Source.Id, 1 /* include other columns to insert here */);