Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL Output Clause: How to access the old Identity ID

I have a T-SQL statement that basically does an insert and OUTPUTs some of the inserted values to a table variable for later processing.

Is there a way for me to store the old Identity ID of the selected records into my table variable. If I use the code below, I get "The multi-part identifier "a.ID" could not be bound." error.

DECLARE @act_map_matrix table(new_act_id INT, old_ID int)
DECLARE @new_script_id int
SET @new_script_id = 1

INSERT INTO Act
(ScriptID, Number, SubNumber, SortOrder, Title, IsDeleted)
OUTPUT inserted.ID, a.ID INTO @act_map_matrix
    SELECT 
        @new_scriptID, a.Number, a.SubNumber, a.SortOrder, a.Title, a.IsDeleted
    FROM Act a WHERE a.ScriptID = 2

Thanks!

like image 613
Jaime Avatar asked Nov 19 '09 20:11

Jaime


1 Answers

I was having your same problem and found a solution at http://sqlblog.com/blogs/adam_machanic/archive/2009/08/24/dr-output-or-how-i-learned-to-stop-worrying-and-love-the-merge.aspx

Basically it hacks the MERGE command to use that for insert so you can access a source field in the OUTPUT clause that wasn't inserted.

MERGE INTO people AS tgt
USING #data AS src ON
    1=0 --Never match
WHEN NOT MATCHED THEN
    INSERT
    (
        name,
        current_salary
    )
    VALUES
    (
        src.name,
        src.salary
    )
OUTPUT
    src.input_surrogate,
    inserted.person_id
INTO #surrogate_map;
like image 159
BrandonAGr Avatar answered Sep 29 '22 15:09

BrandonAGr