Sử dụng MERGE
thay vì 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.*
Cập nhật:
Để làm việc với GROUP BY
vấn đề, sử dụng cái này:
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