我正在从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
答案 0 :(得分:1)
UPDATE investigation
SET investigation.TeamKey = teamMax.maxTeamKey
FROM dbo.Investigation
join team
on teamMax.TeamKey = investigation.TeamKey
join (SELECT Teamid, MAX(Teamkey) as maxTeamKey
FROM team
group BY teamid
having count(*) > 1
) teamMax
on teamMax.Teamid = team.teamid
and investigation.TeamKey <> teamMax.maxTeamKey