Using OUTPUT clause to insert value not in INSERTED

前端 未结 2 1886
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-19 05:53

I am writing a stored procedure to process a table belonging to an application and insert values into a table belonging to the same application (so I cannot amend either tab

2条回答
  •  半阙折子戏
    2020-12-19 06:20

    Use MERGE instead of INSERT:

    MERGE
    INTO    trn_temp d
    USING   (
            SELECT  D.DET_DATE, 'SOMETEXT' AS sometext, SUM(D.DET_NET) AS the_sum
            ...
            ) s
    ON      (1 = 0)
    WHEN NOT MATCHED THEN
    INSERT  (TRN_TRAN_DATE, TRN_DESCRIPTION, TRN_AMT)
    VALUES  (det_date, sometext, the_sum)
    OUTPUT  s.*
    

    Update:

    To work around the GROUP BY problem, use this:

    DECLARE @tmp TABLE
            (
            det_primary INT NOT NULL PRIMARY KEY
            )
    
    MERGE
    INTO    register r
    USING   detail d
    ON      (r.det_primary_link = d.det_primary)
    WHEN NOT MATCHED THEN
    INSERT  (det_primary_link, ins_date)
    VALUES  (det_primary, GETDATE())
    OUTPUT  d.det_primary
    INTO    @tmp;
    
    INSERT
    INTO    trn_temp (trn_tran_date, trn_description, trn_amt)
    OUTPUT  INSERTED.*
    SELECT  det_date, 'sometext', SUM(det_net)
    FROM    @tmp t
    JOIN    detail d
    ON      d.det_primary = t.det_primary
    GROUP BY
            det_date
    

提交回复
热议问题