2013-12-12 119 views
19

我的查詢表的SQL Server更新前1記錄

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

TX_Master_PCBAserial_No專欄中,我有10條記錄,但我想更新最新TIMESTAMP2當前日期時間。

上述查詢拋出錯誤:關鍵字 'TOP' 近

不正確的語法。

+0

可能重複http://stackoverflow.com/questions/19584315/sql-update-top-with-order-by) – GolfWolf

+0

儘管問題陳述了SQL-SERVER,對於搜索MySql解決方案的用戶來說,有一種更簡單快捷的方法:UPDATE TX_Master_PCBA SET TIMESTAMP2 = NOW()WHERE SERIAL_NO ='050030309'ORDER BY TIMESTAMP DESC LIMIT 1' –

+0

[SQL update top1 row query](http:// stackov erlang.com/questions/3860975/sql-update-top1-row-query) – fabriciorissetto

回答

21
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 
) 
7

TOP使用具有INSERTUPDATEMERGE,或DELETE,所引用的行不設置在任何順序和ORDER BY子句不能在這些語句直接指定。如果您需要使用TOP以有意義的時間順序插入,刪除或修改行,則必須使用TOP以及在subselect語句中指定的ORDER BY子句。

TOP不能用於分區視圖上的UPDATEDELETE語句。 (在同一個查詢範圍內)不能與OFFSETFETCH組合使用。欲瞭解更多信息,請參閱http://technet.microsoft.com/en-us/library/ms189463.aspx

31
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' 
13

接受卡皮的答案是有缺陷的,如果有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 

參考萊姆斯Rusanu答: - SQL update top1 row query

+0

如果我想在此處使用Join並從該表中設置值, –

2

對於那些誰正在尋找一個線程安全的解決方案來看看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 
) 
3

這也是行之有效的...

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 
[?SQL UPDATE TOP與ORDER BY(的