我想在sql中选择一条记录,然后在一个语句或存储过程中更新它。
所以,我有这样的陈述:
select top 1 ID, TimeStamp, Locked, Deleted
from TableName
where Locked='False' and Deleted='False'
order by TimeStamp asc
如何选择该语句,然后设置Locked =' True'返回记录。
答案 0 :(得分:3)
如果您使用输出子句,则可以通过选择deleted
with cte as (
select top 1
ID,
TimeStamp,
Locked,
Deleted
from TableName
where Locked='False' and Deleted='False'
order by TimeStamp asc
)
update cte
set Locked = 'True'
output deleted.*
答案 1 :(得分:0)
如果您需要锁定,那么我认为这样做会
问题是您无法将top
与update
一起使用。
create table #T (pk int identity primary key, ts timestamp not null, lock bit not null)
insert into #T (lock) values (1), (0), (1), (0), (0);
select *
from #T t
order by t.ts asc;
update tt
set tt.lock = 1
output deleted.*
from ( select top(1) t.*
from #T t with (UPDLOCK ROWLOCK)
where t.lock = 0
--and t.Deleted = 0
order by t.lock
) tt;
select *
from #T t
order by t.ts asc;
drop table #T
通过UPDLOCK,读取和写入之间的值不能改变。
答案 2 :(得分:-1)
您需要退出数据还是只更新数据?
如果它只是更新:
Update Tablename
Set Locked = 'True'
Where Locked = 'False'
and Deleted = 'False'
给出结果:(在udpate之后添加)
select top 1 ID, TimeStamp, Locked, Deleted
from TableName
where Locked = 'True'
and Deleted = 'False'
order by TimeStamp asc