2013-10-25 28 views
17

我有以下查詢:使用ORDER BY的SQL UPDATE TOP?

UPDATE TOP (@MaxRecords) Messages 
SET status = 'P' 
OUTPUT inserted.* 
FROM Messages 
where Status = 'N' 
and InsertDate >= GETDATE() 

郵件表有優先權列,我想先seleci高優先級消息。所以我需要一個ORDER BY。但是,在更新運行之前,我不需要對排序後的輸出進行排序。

據我所知,不可能將ORDER BY添加到UPDATE語句。任何其他想法?

m。

+1

[SQL更新top1行查詢]的可能重複(http://stackoverflow.com/questions/3860975/sql-update-top1-row-query) – fabriciorissetto

+0

可能重複[如何使用ms sql進行更新和排序](http://stackoverflow.com/questions/655010/how-to-update-and-order-by-using-ms-sql) – Athafoud

回答

27

子查詢,你可以使用公共表表達式是:

;with cte as (
    select top (@MaxRecords) 
     status 
    from Messages 
    where Status = 'N' and InsertDate >= getdate() 
    order by ... 
) 
update cte set 
    status = 'P' 
output inserted.* 

這一個使用事實上,在SQL Server中可以更新cte,就像更新視圖一樣。

-6

更新的正確語法是

UPDATE [LOW_PRIORITY] [IGNORE] table_reference 
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ... 
[WHERE where_condition] 
[ORDER BY ...] 
[LIMIT row_count] 
+0

不在Sql Server中。 – mark

12

你可以嘗試像

UPDATE Messages 
    SET status = 'P' 
    WHERE MessageId IN (SELECT TOP (@MaxRecords) MessageId FROM Messages where Status = 'N' and InsertDate >= GETDATE() ORDER BY Priority) 
output inserted.* 
+0

在我的情況下,我沒有使用TOP,因爲我想通過WHERE子句更新所有匹配的記錄,並且出現錯誤:「ORDER BY子句在視圖,內聯函數,派生表,子查詢和公用表表達式中無效,除非還指定了TOP,OFFSET或FOR XML。「添加一個虛擬TOP(100000)使其工作。我不知道在我的情況下是否有更好的解決方案。 –

+2

@AugustBarreto你可以使用「最高100%」取代所有記錄而不是虛擬號碼。 – Athafoud

+0

謝謝!我不知道。閱讀文檔:「將查詢結果集中返回的行限制爲指定的行數或行數百分比」 –