我有一个带有Deleted
标志(bit
)列的表格。怎么可能实现呢?
在以下条件下列:
如果记录是新的或更新的,请设置为1
如果从源中删除,请设为0
我认为可以在合并声明中进行。但我不知道该怎么做。或许还有另一种方式?
答案 0 :(得分:0)
我认为您可以使用合并语句来执行此操作:
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。
答案 1 :(得分:0)
您可能需要仔细检查您的要求,因为Deleted
标记的标准为0
表示未删除,1
表示已删除。 0
为false,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 */);