与CTE相互引用合并

时间:2019-11-08 14:17:48

标签: sql sql-server common-table-expression sql-merge

在另一个问题中,我有一些需要帮助的代码,这与之相关,但仅部分相关。想到了用更好的东西代替光标。我以为可能是合并的CTE,但是我很难弄清楚如何将合并中的使用与我的CTE联系起来。在下面的代码中,@ REFCOUNTER最初来自我的光标。现在,我正在考虑合并,而不是使用游标,但如何将合并中的using连接到@refcounter。我希望这是有道理的。

如果有后续记录引用CTE,则CTE旨在查找原始计数器值。它从最新记录回到原始记录。

WITH n(COUNTER, REFCOUNTER) AS 
(
    SELECT 
            cnt.COUNTER, 
            cnt.REFCOUNTER 
    FROM 
            TCATMSTR_COUNTER cnt
    WHERE 
            cnt.COUNTER = @REFCOUNTER
UNION ALL
    SELECT 
            nplus1.COUNTER, 
            nplus1.REFCOUNTER 
    FROM 
            TCATMSTR_COUNTER as nplus1, 
            n
    WHERE 
            n.COUNTER = nplus1.REFCOUNTER
)
MERGE INTO TCATMSTR_TEMP mstr
USING
    (
        SELECT 
            CATSHOURS,
            COUNTER,
            (SELECT COUNTER FROM n WHERE REFCOUNTER = '') AS orig_counter,
            PERNR,
            REFCOUNTER,
            CATS_STATUS,
            WORKDATE,
            APDAT,
            LAETM,
            APPR_STATUS
        FROM 
            CATSDB
        WHERE
                (WORKDATE >= '1/1/2019' AND WORKDATE <= '1/11/2019' ) OR
                (APDAT >= '1/1/2019' AND APDAT <= '1/11/2019')
        ORDER BY 
                pernr, WORKDATE, ERSDA, ERSTM, APDAT, LAETM
    ) cats ON cats.orig_counter = mstr.counter
WHEN MATCHED THEN 
    UPDATE SET
        CATSHOURS = cats.CATSHOURS,
        PERNR = cats.PERNR,
        REFCOUNTER = cats.REFCOUNTER,
        CATS_STATUS = cats.CATS_STATUS,
        WORKDATE = cats.WORKDATE,
        APDAT = cats.APDAT,
        LAETM = cats.LAETM,
        APPR_STATUS = cats.APPR_STATUS
WHEN NOT MATCHED THEN
    INSERT
        (
            CATSHOURS,
            COUNTER,
            PERNR,
            REFCOUNTER,
            CATS_STATUS,
            WORKDATE,
            APDAT,
            LAETM,
            APPR_STATUS
        )
    VALUES
        (
            cats.CATSHOURS,
            cats.COUNTER,
            cats.PERNR,
            cats.PLANS,
            cats.REFCOUNTER,
            cats.CATS_STATUS,
            cats.WORKDATE,
            cats.APDAT,
            cats.LAETM,
            cats.APPR_STATUS
        );

0 个答案:

没有答案