views:

87

answers:

1

I am managing a data warehouse. I have several dimension tables most of which are type-2 and some are type-1.

I was able to figure out how to use MERGE to maintain my type-1 dimension tables.

I am stumped on how to do the type-2 dimension tables.

How do I do both, the update to the EndDate and an insert using the MERGE Command?

+1  A: 

MERGE will, unfortunately, not let you apply multiple actions to one condition, or let you operate multiple times on one row.

So, what I do is use an INSERT INTO wrapping up the MERGE:

INSERT INTO DimTable
SELECT ID, Name, StartDate, null as EndDate
FROM
    (
        MERGE DimTable AS tgt
        USING StageTable AS src
            ON tgt.id = src.id AND tgt.enddate IS NULL
        WHEN MATCHED THEN
            UPDATE SET tgt.enddate = src.startdate
        WHEN NOT MATCHED THEN
            INSERT INTO (ID, Name, StartDate) 
                VALUES (src.id, src.name, src.startdate)
        OUTPUT $action as Action, src.ID, src.Name, src.StartDate
    ) a

WHERE
    a.Action = 'UPDATE'

The key there is the OUTPUT clause which will actually redirect those rows so you know exactly what happened to them. A brilliant feature, really.

Eric
@Eric: actually, it will let me issue multiple commands on a NO MATCH, but will not let me have multiple commands on a MATCH. check out this BOL example ms-help://MS.SQLCC.v10/MS.SQLSVR.v10.en/s10de_1devconc/html/952595a6-cf1d-4ff5-8927-66f9090cf79d.htm
Raj More
That link's not working for me, but I did alter it to use one `merge` command wrapped in an `insert into`. I actually have used that, but completely blanked when I first answered.
Eric
@Eric, dude.. you are the BOMB
Raj More
@Eric, I am going to post a follow up question. I will need the table structure so I can talk in concrete terms. I will update a link here to that question.
Raj More