首页 > 解决方案 > SCD Type 2 by Merge Statement 用于跟踪无唯一键的联接表的更改

问题描述

我有一个要SCD Type 2使用创建的表T-SQL Merge statement,但是它没有唯一键。

RoleTaskTable:
RoleID, TaskID
1,A
1,B
1,C
2,A
2,D
2,F
3,A
3,B
3,E
3,F

显然我得到了错误

"The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows."

当我结合RoleIDTaskID作为临时表和 SCDTable 的唯一索引时,它会简单地将其识别为新记录,因此所有记录(即使某些记录已被删除)在 SCD 表中仍标记为活动。

你怎么能解决这样的事情?

我可以展示我为这个 SCD 拥有的整个代码,但我想我在这里错过了一些基本的东西。

标签: sql-servertsqlsql-server-2012scd

解决方案


一个听起来很明显的风险,给表一个唯一的键。没有一个,它就不是一种适当的关系。Merge 旨在使用唯一键。

OTOH,由于 Merge 只是插入/更新/删除的一站式商店,因此您可以使用包装在事务中的各个命令来完成相同的事情。


推荐阅读