how can I Update top 100 records in sql server

前端 未结 7 1058
醉梦人生
醉梦人生 2020-11-27 10:03

I want to update the top 100 records in SQL Server. I have a table T1 with fields F1 and F2. T1 has 200 records. I want

相关标签:
7条回答
  • 2020-11-27 10:21

    Try:

    UPDATE Dispatch_Post
    SET isSync = 1
    WHERE ChallanNo 
    IN (SELECT TOP 1000 ChallanNo FROM dbo.Dispatch_Post ORDER BY 
    CreatedDate DESC)
    
    0 讨论(0)
  • 2020-11-27 10:23

    Without an ORDER BY the whole idea of TOP doesn't make much sense. You need to have a consistent definition of which direction is "up" and which is "down" for the concept of top to be meaningful.

    Nonetheless SQL Server allows it but doesn't guarantee a deterministic result.

    The UPDATE TOP syntax in the accepted answer does not support an ORDER BY clause but it is possible to get deterministic semantics here by using a CTE or derived table to define the desired sort order as below.

    ;WITH CTE AS 
    ( 
    SELECT TOP 100 * 
    FROM T1 
    ORDER BY F2 
    ) 
    UPDATE CTE SET F1='foo'
    
    0 讨论(0)
  • 2020-11-27 10:32

    What's even cooler is the fact that you can use an inline Table-Valued Function to select which (and how many via TOP) row(s) to update. That is:

    UPDATE MyTable
    SET Column1=@Value1
    FROM tvfSelectLatestRowOfMyTableMatchingCriteria(@Param1,@Param2,@Param3)
    

    For the table valued function you have something interesting to select the row to update like:

    CREATE FUNCTION tvfSelectLatestRowOfMyTableMatchingCriteria
    (
        @Param1 INT,
        @Param2 INT,
        @Param3 INT
    )
    RETURNS TABLE AS RETURN
    (
        SELECT TOP(1) MyTable.*
        FROM MyTable
        JOIN MyOtherTable
          ON ...
        JOIN WhoKnowsWhatElse
          ON ...
        WHERE MyTable.SomeColumn=@Param1 AND ...
        ORDER BY MyTable.SomeDate DESC
    )
    

    ..., and there lies (in my humble opinion) the true power of updating only top selected rows deterministically while at the same time simplifying the syntax of the UPDATE statement.

    0 讨论(0)
  • 2020-11-27 10:32

    You can also update from select using alias and join:

    UPDATE  TOP (500) T
    SET     T.SomeColumn = 'Value'
    FROM    SomeTable T
            INNER JOIN OtherTable O ON O.OtherTableFK = T.SomeTablePK
    WHERE   T.SomeOtherColumn = 1
    
    0 讨论(0)
  • 2020-11-27 10:34
    update tb set  f1=1 where id in (select top 100 id from tb where f1=0)
    
    0 讨论(0)
  • 2020-11-27 10:46

    Note, the parentheses are required for UPDATE statements:

    update top (100) table1 set field1 = 1
    
    0 讨论(0)
提交回复
热议问题