Search This Blog

Update Top 10 in SQL

Update Top 10  in SQL 

Update query update all values of a column when no where condition is defined.

I met a scenario when in my table there were thousands of records and  in one column who has  lots of null values and the table was not having any autoincreamented field.
I have to update some of Null Records with some values ,other null records with other values and so on....

So below are the steps to update top 10 or 100 or any number of records of a column

--Scenario 1 update using Update statement

create table Tbl1 (C1 int, c2 varchar(100))

select * from Tbl1 

insert into Tbl1 values(2,'4'),(3,'6'),(4,'10')

insert into Tbl1 values (5,null),(6,null),(9,null)

Now we want to update col2 having null but the restriction is we don't' have any autoincreament column based on which we can update
here the table has less record so you can update by adding where condition but when there are very large no. of records and you have to update top record then you have to use below query


--Its necessary to have brackets in top clause when using with update

update top(2) Tbl1 set c2 ='10'

 (This case is used when you want to update null values with limitations of rows)

Now we can also update remaining null fields using cte

--Update using Cte

with cte as (

select * from Tbl1 where c2 is null
)

update cte set c2 =20

NOTE : Update through CTE can only be posible when CTE select query is fetching data from single table (not using Joins).




No comments:

Post a Comment