0

I am trying to loop through my records with a where clause.

I am trying to get only top 100 rows first and then next 100 (some logic i apply with what i get in the select clause)

But, if the first 100 rows does not return a result, it does not goes into 2nd 100 set of data.

My query is :

DECLARE @BatchSize INT = 100
DECLARE @Counter INT = 0
DECLARE @TableCount INT = 0
set @TableCount = (select count(*) from Table1)  //@TableCount = 10000

while @Counter < @TableCount/@BatchSize //@Counter < 100
BEGIN        
    SET @Counter=@Counter+1
    INSERT INTO Table4
    SELECT TOP(@BatchSize) * FROM Table2 
    WHERE NOT EXISTS (SELECT * Table3) and some condition

Here, If i dont get the data for first 100 rows, it wont go to next 100 set of data.

What should I do ?

9
  • Loops and SQL are usually an indication you're not thinking in terms of Sets. You really want to think in terms of Sets. Commented May 16, 2016 at 21:44
  • Why would you want to do this? Commented May 16, 2016 at 21:45
  • @JoelCoehoorn Can you explain me more about this. I didnt understood, I am doing loops because I have millions of rows of data and i dont want to lock the whole table. Commented May 16, 2016 at 21:45
  • Loops are worse for locking than just running the query. Commented May 16, 2016 at 21:46
  • 1
    "I want to move the data in other table" Try a SELECT INTO query instead. Commented May 16, 2016 at 21:47

1 Answer 1

1

Instead of TOP @BatchSize in the SELECT clause, try OFFSET @BatchSize * @Counter FETCH NEXT @Batchsize ROWS ONLY after the WHERE clause.

Based on comments, you may also want to look into a SELECT INTO query, as well as the nolock query hint.

Sign up to request clarification or add additional context in comments.

5 Comments

I edited the question, Can you let me know how should I use OFFSET here ? Or select into ?
don't you need ORDER BY for OFFSET?
@JamieD77 Yes, but you need an ORDER BY to guarantee consistency for his loop, too.
Ok, I got the anser by offset, so what do you suggest ? I should not go with it ? Or select into ?
@JoelCoehoorn The Select Into will lock the whole database. I dont want that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.