Home Forums SQL Server 2008 T-SQL (SS2K8) join/merge 2 status tables (check statuses at any change) RE: join/merge 2 status tables (check statuses at any change)

  • I agree with Alan.B that you've got a pretty good way already figured out. I also agree with his comment about named columns, but I assume these are just for example.

    There is another way that might be just a smidgen swifter, but you'd need to run a timing test to be sure. That is to use a Quirky Update.

    SELECT [Object], [Date], status1, status2

    INTO #Temp

    FROM

    (

    SELECT [Object], status1=NULL, status2, [date]

    FROM table2

    UNION ALL

    SELECT [Object], status1, NULL, [date]

    FROM table1

    ) a;

    DECLARE @status1 nvarchar(1000)

    ,@status2 nvarchar(1000);

    ALTER TABLE #Temp ALTER COLUMN [Date] DATETIME NOT NULL;

    ALTER TABLE #Temp ADD PRIMARY KEY([Date]);

    UPDATE #Temp WITH(TABLOCKX)

    SET @Status1 = Status1 = CASE WHEN Status1 IS NULL THEN @Status1 ELSE Status1 END

    ,@Status2 = Status2 = CASE WHEN Status2 IS NULL THEN @Status2 ELSE Status2 END

    OPTION (MAXDOP 1);

    SELECT * FROM #Temp ORDER BY [Object], [Date];

    GO

    DROP TABLE #Temp;

    You should carefully read the section on the QU in this article: Solving the Running Total and Ordinal Rank Problems[/url] by Jeff Moden so that you understand the rules that apply when using the QU.

    Initially I wrote that SQL 2012 might have a analytic function (LAG) that might make short work of this problem but I'm now not so sure, as an initial attempt didn't result in anything fruitful. There still could be a way I just don't have the time at the moment to play with it.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St