SQL Server存储过程选择/更新/返回

时间:2011-03-24 19:45:42

标签: sql-server stored-procedures

我正在尝试编写一个SQL Server存储过程,从表中选择顶行,更新该行中的列,然后返回包含更改的行。

例如:

  1. row = SELECT TOP 1 FROM Requests
  2. UPDATE Requests SET row.Locked = True
  3. RETURN row
  4. 我似乎无法做到这一点。有人能指出我正确的方向吗?

2 个答案:

答案 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