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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 07:48:11  来源:igfitidea点击:

SQL update top1 row query

sqlsql-serversql-server-2008

提问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 SETand WHERE)

如果你想返回更新项目的某些列,你可以把它放在你的更新语句中:(OUTPUT INSERTED.AccountIdSET和之间WHERE