我正在从 DW 中删除一些 SCD,因为它们不是必需的,并且使用会产生大量重复的 SELECT EXCEPT 语句来实现。我想重定向事实表中的引用,这样我们就没有孤立的记录。我设法使用下面的光标来完成此操作(我认为)。只是想知道是否有更流畅的方法?
DECLARE RemoveOldKeys CURSOR READ_ONLY
FOR
SELECT Teamid ,
MAX(Teamkey) -- latest surrogate key value generated by SCD code that is to be removed
FROM dbo.Team c1
WHERE EXISTS ( SELECT teamid , -- select entries from the team table in DW that have more than entry
COUNT(*)
FROM dbo.team c2
WHERE c1.teamid = c2.teamid
GROUP BY teamid
HAVING COUNT(*) > 1 )
GROUP BY teamid
ORDER BY c1.teamid
DECLARE @teamid UNIQUEIDENTIFIER ,
@CurrentTeamkey INT
OPEN RemoveOldKeys
FETCH NEXT FROM RemoveOldKeys INTO @teamid, @CurrentTeamKey
WHILE @@fetch_status = 0
BEGIN
UPDATE investigation
SET investigation.TeamKey = @CurrentTeamKey
FROM dbo.Investigation i
INNER JOIN dbo.Team t ON t.TeamKey = i.TeamKey
WHERE t.teamID = @teamID
AND i.teamkey <> @CurrentTeamKey -- no need to update if the key is already correct
FETCH NEXT FROM RemoveOldKeys INTO @teamid, @CurrentTeamKey
END
CLOSE RemoveOldKeys
DEALLOCATE RemoveOldKeys
GO