T-SQL合并语句类型2



我正在试验合并语句,最终使用它来创建一个SCD类型2的加载过程。我正在寻找的行为是:

  • source中的新记录—>插入目标
  • 在源代码中更新记录->结束和停用目标记录,并在目标中添加新记录。
  • 源文件中已删除的记录——>目标记录的结束日期,并在目标中添加带有删除日期集的新记录

我已经看到使用合并语句来简单地更新目标表中的记录以设置删除日期,但这不是我想要的。相同的代码输出更新后的记录,用于在发生更新时插入新记录。我计划在删除的情况下使用相同的机制,并在输出(下面的代码)中使用合并来返回正确的值,假设如果插入了一条记录,则删除的值将为NULL。

但是,如果我更新一条记录并运行我的脚本,则删除的集合也包含值(通过转储已删除的集合来测试这一点)。Id列到目标表)。我在源表中更新的id是id 1,在目标表中deleted_idinserted_id都是1。我希望deleted_id为null,inserted_id为1…

以下是我的脚本:

select 
*
FROM
(merge test_rbo as target using test_rbo_source as source on target.id = source.id and target.meta_active = 1
WHEN not matched by target THEN
insert (id, name, meta_load_date, meta_load_end_date, meta_deleted, meta_active, action) values (source.id, source.name, getdate(), '9999-12-31 23:59:59', null, 1, 'INSERT')
WHEN matched and target.name <> source.name THEN
update set target.meta_load_end_date = GETDATE(), meta_active = 0
WHEN not matched by source THEN
update set meta_active = 0
output         
coalesce(deleted.id, source.id) as id,
coalesce(deleted.name, source.name) as name,
getdate() as meta_load_date,
'9999-12-31 23:59:59' as meta_load_end_date,
case when $action = 'DELETE' then getdate() when $action = 'UPDATE' then null end as meta_deleted,
1 as meta_active,
$action as action,
source.id as source_id,
inserted.id as inserted_id,
deleted.id as deleted_id
) as a
WHERE  
action <> 'INSERT';

所以基本上我想知道这是否是正常的行为,如果合并语句甚至适用于我想要的。

谢谢!

使用merge语句是不可能实现的。

最新更新