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

Kap*_*pil 31 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 
Run Code Online (Sandbox Code Playgroud)

使用表中的serial_NoTX_Master_PCBA我有10条记录,但我想更新最新TIMESTAMP2的当前日期时间.

上面的查询抛出错误:

关键字"TOP"附近的语法不正确.

小智 39

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'
Run Code Online (Sandbox Code Playgroud)


Kap*_*pil 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
)
Run Code Online (Sandbox Code Playgroud)


pan*_*rma 19

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
Run Code Online (Sandbox Code Playgroud)

Ref Remus Rusanu Ans: - SQL更新top1行查询


bod*_*di0 12

TOP与使用INSERT,UPDATE,MERGE,或DELETE,被引用的行不设置在任何顺序和ORDER BY子句不能在这些语句直接指定.如果需要使用TOP以有意义的时间顺序插入,删除或修改行,则必须TOPORDER BYsubselect语句中指定的子句一起使用.

TOP不能在使用UPDATEDELETE语句上分区视图.

TOP不能与被组合OFFSETFETCH在相同的查询表达式(在同一查询范围).有关详细信息,请参阅http://technet.microsoft.com/en-us/library/ms189463.aspx


fab*_*tto 8

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

代码:

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 
)
Run Code Online (Sandbox Code Playgroud)

  • +1 线程安全,尽管当 `AccountId` 不是唯一的时,你将不得不在 /sf/answers/2267666761/ 提到的 cte 中工作才能只抓取一条记录。 (2认同)

小智 5

它也很好用...

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
Run Code Online (Sandbox Code Playgroud)