开发者

SQL update top1 row query

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:

update  top(1) ShipBillInfo 
set     shipfirstname='kkk' 
where   CustomerId='134' 
order by 
      开发者_运维技巧  OredrGUID desc;


With cte as (
select  top(1) shipfirtsname  
From ShipBillInfo 
where   CustomerId='134' 
order by  OredrGUID desc)
Update cte set shipfirstname='abc';


why dont you do :

update ShipBillInfo 
set shipfirstname='kkk' 
where OrderGUID = (select top (1) OrderGUID  
                   from ShipBillInfo 
                   where CustomerId = 134 
                   order by OredrGUID desc )


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜