我已经为SCD type2编写了t-SQL Merge语句,它工作正常但是,我想要插入,更新的行数的审计信息。 这是Ex:
insert into dbo.MergegeSCD2
(id, firstname, lastname, CREATE_DTTM, MODIF_DTTM, ARCHV_FLAG, EffectiveFrom, EffectiveTo, CurrentFlag)
select
id, firstname, lastname, CREATE_DTTM, MODIF_DTTM, ARCHV_FLAG, EffectiveFrom, EffectiveTo, CurrentFlag
from
(
--DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20))
MERGE dbo.MergegeSCD2 TT
using dbo.MergegeSCD1 SS
on ss.id=tt.id
WHEN NOT MATCHED THEN
INSERT (id, firstname, lastname, CREATE_DTTM, MODIF_DTTM, ARCHV_FLAG, EffectiveFrom, EffectiveTo, CurrentFlag)
values (id, firstname, lastname, CREATE_DTTM, MODIF_DTTM, ARCHV_FLAG,'1800-01-01', NULL ,1)
WHEN MATCHED and tt.[CurrentFlag] = 1
AND exists
(select ss.id, ss.firstname, ss.lastname, ss.CREATE_DTTM, ss.MODIF_DTTM, ss.ARCHV_FLAG
except
select tt.id, tt.firstname, tt.lastname, tt.CREATE_DTTM, tt.MODIF_DTTM, tt.ARCHV_FLAG
)
THEN UPDATE set tt.[CurrentFlag] = 0
, tt.[EffectiveTo] = ss.[MODIF_DTTM]
OUTPUT $Action Action_Taken
, ss.id, ss.firstname, ss.lastname, ss.CREATE_DTTM, ss.MODIF_DTTM, ss.ARCHV_FLAG
, ss.[MODIF_DTTM] AS [EffectiveFrom]
, NULL AS [EffectiveTo]
,1 AS [CurrentFlag]
)
AS MERGE_OUT
WHERE MERGE_OUT.Action_Taken = 'UPDATE';
select @@ROWCOUNT
我使用select @@ROWCOUNT
获得了更新记录,但我正在为inserted records
而努力。有人可以帮忙吗?
答案 0 :(得分:0)
您可以这样做:
DECLARE @tableVar TABLE
(MergeAction VARCHAR(20),
InsertedID INT)
OUTPUT
$action, inserted.Column_name 'inserted' INTO @tableVar
然后在MERGE广告结束时:
ORDER BY total LIMIT 1
答案 1 :(得分:0)
为了跟踪SCD2 Merge语句中插入的行,我通常在Merge语句之后采用以下脚本:
SELECT COUNT(*) FROM dbo.table_target WHERE valid_from = @begin_in_date AND loadid = @loadid
到目前为止,没有找到更好的解决方案。