how can I Update top 100 records in sql server

Viewed 531345

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?

9 Answers

Note, the parentheses are required for UPDATE statements:

update top (100) table1 set field1 = 1
update tb set  f1=1 where id in (select top 100 id from tb where f1=0)

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

Try:

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

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;

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.

Related