更新表sql server中的前1条记录

时间:2013-12-12 09:04:02

标签: sql-server sql-server-2008

我的查询

UPDATE TOP (1) TX_Master_PCBA  
SET TIMESTAMP2 = '2013-12-12 15:40:31.593'
WHERE SERIAL_NO IN ('0500030309') 
ORDER BY TIMESTAMP2 DESC 

serial_No表中的TX_Master_PCBA列我有10条记录,但我想将最新的TIMESTAMP2更新为当前日期时间。

以上查询引发错误:

  

关键字“TOP”附近的语法不正确。

6 个答案:

答案 0 :(得分:38)

WITH UpdateList_view AS (
  SELECT TOP 1  * from TX_Master_PCBA 
  WHERE SERIAL_NO IN ('0500030309') 
  ORDER BY TIMESTAMP2 DESC 
)

update UpdateList_view 
set TIMESTAMP2 = '2013-12-12 15:40:31.593'

答案 1 :(得分:22)

UPDATE TX_Master_PCBA
SET TIMESTAMP2 = '2013-12-12 15:40:31.593',
G_FIELD='0000'
WHERE TIMESTAMP2 IN 
(
   SELECT TOP 1 TIMESTAMP2
   FROM TX_Master_PCBA WHERE SERIAL_NO='0500030309'
   ORDER BY TIMESTAMP2 DESC   -- You need to decide what column you want to sort on
)

答案 2 :(得分:15)

Kapil的已接受答案存在缺陷,如果有2条或多条记录具有相同的时间戳,则会更新多条记录,而不是真正的前1条查询。

    ;With cte as (
                    SELECT TOP(1) email_fk FROM abc WHERE id= 177 ORDER BY created DESC   
            )
    UPDATE cte SET email_fk = 10

Ref Remus Rusanu Ans: - SQL update top1 row query

答案 3 :(得分:12)

TOPINSERTUPDATEMERGEDELETE一起使用时,引用的行不按任何顺序排列,并且ORDER BY子句不能在这些语句中直接指定。如果需要使用TOP以有意义的时间顺序插入,删除或修改行,则必须将TOP与子选择语句中指定的ORDER BY子句一起使用。

TOP不能在分区视图的UPDATEDELETE语句中使用。

TOP无法与同一查询表达式中的OFFSETFETCH结合使用(在同一查询范围内)。有关详细信息,请参阅http://technet.microsoft.com/en-us/library/ms189463.aspx

答案 4 :(得分:4)

它也运作良好......

Update t
Set t.TIMESTAMP2 = '2013-12-12 15:40:31.593'
From
(
    Select Top 1 TIMESTAMP2
    From TX_Master_PCBA
    Where SERIAL_NO IN ('0500030309')
    Order By TIMESTAMP2 DESC
) t

答案 5 :(得分:3)

对于那些寻找线程安全解决方案的人,请查看here

代码:

UPDATE Account 
SET    sg_status = 'A'
OUTPUT INSERTED.AccountId --You only need this if you want to return some column of the updated item
WHERE  AccountId = 
(
    SELECT TOP 1 AccountId 
    FROM Account WITH (UPDLOCK) --this is what makes the query thread safe!
    ORDER  BY CreationDate 
)