0

I have a stored proc that has a merge .. into statement. I am trying to get the value of the primary key out of the stored proc.

 SET @NewCompanyID  = @CompanyID  
 ....
 merge company as c
 using ( select @CompanyID) as compAlt (company_id )
 on compAlt.company_id = c.company_id
 when matched 
 then 
    update set ....
 when not matched 
 then 
     insert ...    ;


  SET @NewCompanyID = @@identity; 

If the merge statement runs the update, i want to set @NewCompanyID to whatever value was passed into the stored proc (@CompanyID). If the insert statement was executed, then I want to pass the @@identity. How do I do this?

CFNinja
  • 3,571
  • 4
  • 38
  • 59

1 Answers1

0

I added before merge into

 DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));

then

  OUTPUT $action INTO @SummaryOfChanges;

 SELECT @Change = Change
        FROM @SummaryOfChanges;     /* there is always one update or insert */

        IF @Change = 'INSERT'
        BEGIN
            ....
        END

This worked fine.

CFNinja
  • 3,571
  • 4
  • 38
  • 59