sql-servert-sqlcursorscd2

Avoiding orphaned Records after removing SCD


I am removing some SCDs from a DW as they are not required and implemented using SELECT EXCEPT statements that are producing large number of duplicates. I want to redirect the references in the fact table so we don't have orphaned records. I managed to accomplish this using the cursor below (I think). Just Wondered if there was a slicker way?

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

Solution

  • 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