我正在尝试编写一个SQL Server存储过程,从表中选择顶行,更新该行中的列,然后返回包含更改的行。
例如:
row = SELECT TOP 1 FROM Requests
UPDATE Requests SET row.Locked = True
RETURN row
我似乎无法做到这一点。有人能指出我正确的方向吗?
答案 0 :(得分:3)
update top(1) Request
set Locked = 1
output inserted.*
where Locked = 0
当您需要按顺序获取要修改的行时的版本。
在这里,您将Locked=1
设置为DateField
Locked = 0
值
测试数据
create table Request(ID int, Locked bit, DateField datetime)
insert into Request values (1, 0, '20010101')
insert into Request values (2, 0, '20010102')
insert into Request values (3, 0, '20010103')
使用cte更新语句
;with cte as
(
select *,
row_number() over(order by DateField desc) as rn
from Request
where Locked = 0
)
update cte
set Locked = 1
output inserted.ID, inserted.Locked, inserted.DateField
where rn = 1
结果
ID Locked DateField
----------- ------ -----------------------
3 1 2001-01-03 00:00:00.000
如果您想使用inserted.*
而不是在output子句中指定字段,则可以执行此操作。
update Request
set Locked = 1
output inserted.*
from Request as r
inner join
(select ID, row_number() over(order by DateField desc) as rn
from Request
where Locked = 0) as rs
on r.ID = rs.ID and
rs.rn = 1
答案 1 :(得分:2)
您可以使用OUTPUT子句:
DECLARE @Results TABLE (SomeField INT)
UPDATE TOP (1) Requests
SET Locked = 1
OUTPUT inserted.SomeField INTO @Results (SomeField)
SELECT * FROM @Results