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
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
I know this question is nearly a year old, but your insert can work as you have presented it if you select the proper column name from the OUTPUT
The output clause gives us one of two possible virtual tables, inserted or deleted, depending on the operation, an update operation gives both. Since you don't have a field name DET_DATE in your TRN_TEMP table that you just inserted into, it is invalid in the output statement.
INSERT INTO TRN_TEMP (TRN_TRAN_DATE, TRN_DESCRIPTION, TRN_AMT)
OUTPUT INSERTED.TRN_TRAN_DATE, GETDATE()
INTO REGISTER (DET_PRIMARY_LINK, INS_DATE)
SELECT D.DET_DATE, 'SOMETEXT', SUM(D.DET_NET)
FROM DETAIL D
LEFT JOIN REGISTER R ON D.DET_PRIMARY = R.DET_PRIMARY_LINK
WHERE <MY CONDITIONS> AND R.LINE_ID IS NULL -- TO REMOVE LINES ALREADY PROCESSED
GROUP BY D.DET_DATE