ChatGPT解决这个技术问题 Extra ChatGPT

how can I Update top 100 records in sql server

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 to update the F1 field in the top 100 records. How can I update based on TOP 100 in SQL Server?


S
Sean

Note, the parentheses are required for UPDATE statements:

update top (100) table1 set field1 = 1

Any idea how to use the order by as well?
@JoePhilllips Use the Martin Smith answer for order by
These are not the top 100 records, however, but simply 100 arbitrarily chosen records. Top 100 would include some order to rank the records.
This answers the question "as asked" but TOP is meaningless (and unpredictable) without some ORDER. See the answer further down by Martin Smith.
It's not meaningless if you're trying to update a large table in chunks, but that would require a WHERE clause (such as WHERE field1 IS NULL). So yes TOP is meaningless without either ORDER BY or a WHERE clause - and for both cases an index is required for large tables to be efficient.
M
Martin Smith

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'

You say meaningless but that's not true. I admit that, /usually/, when you're using TOP odds are you should be using it with ORDER BY because what you're interested in is like the "most" or "least" of something. In other cases, however, you may only be interested in getting one matching record. Like me today! I needed to fix data issues (cycles) one at a time. The entire fix process involved a db script, some user intervention, and some application operations. We didn't care WHICH record was handled first. We just cared that we were handling them one at a time.
@MetaFight But then you would have had a WHERE clause to exclude previously processed records. The question as written and accepted answer are pretty meaningless. BTW: For using tables as a queue this is quite a useful link
I need to use top without order by so that I can run an asynchronous process. The where clause will not include those that have already been processed, but I can only process so many at a time. So it has a perfectly valid use case.
@Martin Smith: Let's say you want to update in batches, say 10000 at a time. Seems like a good use for this, and order doesn't matter. How does this "not make sense"?
@notfed This is the same case as has already been discussed to death in the comments above. Your query in that case would not look like the one in the accepted answer would it? You would need a where clause to avoid processing the same rows again and again.
D
DaveShaw
update tb set  f1=1 where id in (select top 100 id from tb where f1=0)

Will be better to add ORDER BY for deterministic order, .i.e. update tb set f1=1 where id in (select top 100 id from tb where f1=0 order by id asc)
With a mutli-million table this is terribly slow
C
Claudio B

for those like me still stuck with SQL Server 2000, SET ROWCOUNT {number}; can be used before the UPDATE query

SET ROWCOUNT 100;
UPDATE Table SET ..;
SET ROWCOUNT 0;

will limit the update to 100 rows

It has been deprecated at least since SQL 2005, but as of SQL 2017 it still works. https://docs.microsoft.com/en-us/sql/t-sql/statements/set-rowcount-transact-sql?view=sql-server-2017


SET ROWCOUNT affects triggers as well as the command being updated. If you have cascade delete set, it can fail the transaction if more than the rowcount of child rows exist in the child table.
With that said, SET ROWCOUNT @RowCountParameter; is valid syntax, whereas SELECT TOP @RowCountParamter * FROM TableName is invalid. If you need to configure the rows being updated, SET ROWCOUNT # is currently the better option, provided you do not have child tables with cascade delete enabled.
In SQL Server 2017 it is now possible to use @variable in TOP clause: docs.microsoft.com/en-us/sql/t-sql/queries/…
M
Michael Goldshteyn

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.


V
Vanderlei Pires

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

P
Prashant Pimpale

Try:

UPDATE Dispatch_Post
SET isSync = 1
WHERE ChallanNo 
IN (SELECT TOP 1000 ChallanNo FROM dbo.Dispatch_Post ORDER BY 
CreatedDate DESC)

What is the difference with previous hyyxing's how can I Update top 100 records in sql server answer?
B
BATUHAN TOKAN

this piece of code can do its job

UPDATE TOP (100) table_name set column_name = value;

If you want to show the last 100 records, you can use this if you need.

With OrnekWith
as
(
Select Top(100) * from table_name Order By ID desc
)
Update table_name Set column_name = value;

J
JohnH

The TOP qualifier can also be used as limit the the number of rows manually updated incorrectly.

Consider the following UPDATE syntax.

UPDATE TOP (1) table1 SET column1 = 0 WHERE column_pk = '123'

Without the TOP clause, if you are doing a manual update and your mouse text selection only selects from "UPDATE" to just before the "WHERE" clause, then the update is applied to ALL rows. With the TOP clause, only one row would get the undesired update.

The TOP constraint can limit the damage of a missing or incorrect WHERE clause or ORDER BY clause. This can be helpful when it is known that only one or a few rows should be updated.