问题
I am using SQL Server 2008
I have a table named MYTABLE
with two columns: ID
, STATUS
I want to write a stored procedure that returns the records whose STATUS
is 0. But this stored proc must update the STATUS
of returned rows to 1. How can I do this selecting and updating operation in a single query?
回答1:
update MyTable
set Status = 1
output inserted.*
where Status = 0
If you want to return what the table looked like before the update you should use deleted.* instead.
update MyTable
set Status = 1
output deleted.*
where Status = 0
You can of course use both if you like and you don't have to use *
. You can specify the columns you are interested in.
update MyTable
set Status = 1
output inserted.ID, inserted.status, deleted.status as OldStatus
where Status = 0
回答2:
Can probably be done using the OUTPUT clause.
来源:https://stackoverflow.com/questions/6402103/sql-update-updating-selected-rows