SQL 更新 top1 行查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3860975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL update top1 row query
提问by Tina
The query below is working:
下面的查询正在运行:
update top(1) ShipBillInfo
set shipfirstname='kkk'
where CustomerId='134';
but it is showing error if i try to order by some Id: for example:
但是如果我尝试按某个 Id 订购它会显示错误:例如:
update top(1) ShipBillInfo
set shipfirstname='kkk'
where CustomerId='134'
order by
OredrGUID desc;
回答by Remus Rusanu
With cte as (
select top(1) shipfirtsname
From ShipBillInfo
where CustomerId='134'
order by OredrGUID desc)
Update cte set shipfirstname='abc';
回答by storm_buster
why dont you do :
你为什么不这样做:
update ShipBillInfo
set shipfirstname='kkk'
where OrderGUID = (select top (1) OrderGUID
from ShipBillInfo
where CustomerId = 134
order by OredrGUID desc )
回答by fabriciorissetto
Thread Safe
线程安全
For a thread safe solution none of the proposed solutions worked for me (some rows got updated more than once when executed it at the same time).
对于线程安全的解决方案,没有一个建议的解决方案对我有用(某些行在同时执行时更新了不止一次)。
This worked:
这有效:
UPDATE Account
SET sg_status = 'A'
WHERE AccountId =
(
SELECT TOP 1 AccountId
FROM Account WITH (UPDLOCK) --this makes it thread safe
ORDER BY CreationDate
)
If you want to return some column of the updated item you can put this in your update statement: OUTPUT INSERTED.AccountId
(between the SET
and WHERE
)
如果你想返回更新项目的某些列,你可以把它放在你的更新语句中:(OUTPUT INSERTED.AccountId
在SET
和之间WHERE
)