Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Stored Procedure that returns updated records

I'm trying to create a stored proc that returns all records that are updated.

My update query is this:

UPDATE BatchItems 
SET [Status] = 'Processing' 
WHERE [Status] = 'Queued'

I'm just not sure how to return those specific records.

like image 710
Great Gonzo Avatar asked Feb 24 '23 08:02

Great Gonzo


1 Answers

You can use OUTPUT INSERTED.[cols] to fetch rows the statement has modified.

UPDATE BatchItems 
   SET [Status] = 'Processing' 
   OUTPUT INSERTED.*
WHERE [Status] = 'Queued'

Example;

select 'Queued       ' as status, 1 as id into #BatchItems
insert  #BatchItems values ('Queued', 2)
insert  #BatchItems values ('XXX', 3)

UPDATE #BatchItems 
  SET [Status] = 'Processing' 
  OUTPUT INSERTED.*
WHERE [Status] = 'Queued'

>>status       id
>>Processing   2
>>Processing   1
like image 134
Alex K. Avatar answered Feb 26 '23 02:02

Alex K.