sql-server - 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."
当我结合RoleID
并TaskID
作为临时表和 SCDTable 的唯一索引时,它会简单地将其识别为新记录,因此所有记录(即使某些记录已被删除)在 SCD 表中仍标记为活动。
你怎么能解决这样的事情?
我可以展示我为这个 SCD 拥有的整个代码,但我想我在这里错过了一些基本的东西。
解决方案
一个听起来很明显的风险,给表一个唯一的键。没有一个,它就不是一种适当的关系。Merge 旨在使用唯一键。
OTOH,由于 Merge 只是插入/更新/删除的一站式商店,因此您可以使用包装在事务中的各个命令来完成相同的事情。
推荐阅读
- firebase - 确保用户在登录之前验证了他们的电子邮件
- websocket - 无法从 CloudRun 连接到 Websocket
- c++ - 什么是 istream_view 以及何时使用?
- clang - 如何将 libstdc++ 与 clang 一起使用?
- cors - AMP 电子邮件表单导致错误 [amp-form] 表单提交失败:错误:请求 viewerRenderTemplate 失败:错误:Class$obf_1008:
- node.js - Discord.js 12.5.1 错误:找不到模块“./GuildTemplate”
- r - 在 data.table 中使用 Reduce() 时跳过 NA
- python - python随机数生成器函数
- java - 如何为批量摄取项目决定 Xmx 的堆大小
- python - 你如何在 Pygame 中以较低的不透明度对精灵进行 blit/绘制?