복붙노트

[SQL] ORDER BY와 SQL UPDATE TOP?

SQL

ORDER BY와 SQL UPDATE TOP?

나는 다음과 같은 쿼리를 가지고 :

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

메시지 테이블에서이 우선 순위 열 내가 먼저 우선 순위가 높은 메시지를 선택합니다. 나는 BY 주문을해야합니다 그래서. 하지만 정렬 된 출력이 필요하지만 업데이트를 실행하기 전에 데이터를 정렬되지 않습니다.

내가 아는 한 그것은 UPDATE 문에 ORDER BY를 추가 할 수 없습니다. 어떤 다른 아이디어?

해결법

  1. ==============================

    1.이 공통 테이블 식을 사용할 수 있습니다 :

    이 공통 테이블 식을 사용할 수 있습니다 :

    ;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 서버에 업데이트 할보기와 같은 업데이트 CTE에 가능하다는 사실을 사용합니다.

  2. ==============================

    2.당신은 같은 서브 쿼리를 시도 할 수 있습니다

    당신은 같은 서브 쿼리를 시도 할 수 있습니다

      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.*
    
  3. ==============================

    3.업데이트의 올바른 구문은

    업데이트의 올바른 구문은

    UPDATE [LOW_PRIORITY] [IGNORE] table_reference
    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
    [WHERE where_condition]
    [ORDER BY ...]
    [LIMIT row_count]
    
  4. from https://stackoverflow.com/questions/19584315/sql-update-top-with-order-by by cc-by-sa and MIT license