SQL Update - Updating selected rows

删除回忆录丶 提交于 2020-01-14 01:46:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!