我正在尝试通过 T-SQL 实现缓慢变化的维度类型 2,但我不知道如何使请求生效。
表格列:cpf
, nome
, telefone_update
,endereco_insert
基本上逻辑是:如果使用MATCH
没有发生cpf
,则必须插入记录;如果MATCH
发生了但只有telefone_update
字段发生了变化,则不需要另一条记录,我只想更新并覆盖这些值;如果MATCH
发生这种情况但只有endereco_insert
字段发生了变化,我想添加一条新记录并更新开始日期和结束日期。
到目前为止,我所拥有的是:
insert into #dm_lucas_tst (
[cpf],
[nome],
[telefone_update],
[endereco_insert],
[dt_scd_start],
[dt_scd_end],
[nu_scd_version]
)
select [cpf],
[nome],
[telefone_update],
[endereco_insert],
cast(dateadd(month, datediff(month, 0, getdate()), 0) as date) as [dt_scd_start],
'2199-12-31' AS [dt_scd_end],
1 AS [nu_scd_version]
from (
merge edw.dim.dm_lucas_tst as Target
using edw.dim.stg_lucas_tst as Source
on Target.cpf = Source.cpf
when not matched by target
then
insert (
[cpf],
[nome],
[telefone_update],
[endereco_insert],
[dt_scd_start],
[dt_scd_end],
[nu_scd_version]
)
values (
Source.[cpf],
Source.[nome],
Source.[telefone_update],
Source.[endereco_insert],
cast(dateadd(month, datediff(month, 0, getdate()), 0) as date),
'2199-12-31',
1
)
when matched
and Source.telefone_update <> Target.telefone_update
and Target.dt_scd_end = '2199-12-31'
then
update set telefone_update = Source.telefone_update
output $ACTION ActionOut,
Source.[cpf],
Source.[nome],
Source.[telefone_update],
Source.[endereco_insert]
) AS MergeOut
where MergeOut.ActionOut = 'UPDATE';
但我认为放置另一个WHEN MATCH AND ...
不会使这项工作。
有什么建议么?
提前致谢!