Sunday, 23 September 2012

How to update top 100 rows from table in SQL


How to Update top 100 amount of data from a table in SQL

Below codes update top 100 rows. So it never meets the timeout exception and will complete execution faster than normal query
Query for update status of  top 100 data from the table My Table order by date in SQL 


WITH Q as
(
select top 100 * from My_Table order by DATE desc
)
UPDATE Q
SET Status = 0

How to delete large amount of rows from table in SQL

How to delete huge amount of data from a table in SQL

In some scenario we have to delete large amount of rows from sql table and it will going to timeout if the table has very large amount of rows (Some tables in the database has more than crore rows). In this scenario we need to delete some small amount of records and from the table and continue the process until all records in the table deleted.

Query for recursive deletion from the table in SQL 

Below codes delete 50000 rows recursively untill all records int the table deleted. So it never meets the timeout exception and will complete execution faster than normal query


WHILE exists (
SELECT * FROM myTable WHERE name like ‘%ab%’
 )
DELETE TOP (50000) scanned_cont_dtls WHERE name like ‘%ab%’;