0

There were some while loops in a procedure and I want to remove them / replace with temp tables or any other ( not cursor) .

Below I have created a dummy syntax, I have to populate the TEMP_TABLE table based on some calculations. Please share any better option to do the same:

SET @J = 0
SET @DIFFERENCE = 10
SET @INCREMENT = 2

WHILE (@J < @DIFFERENCE) 
BEGIN   
    SET @TO_DATE = (SELECT DATEADD(D, @INCREMENT, @TO_DATE))   

    IF (@TO_DATE <= GETDATE())
       INSERT INTO TEMP_TABLE 
       VALUES(@J, @TO_DATE)   

    SET @J = @J + @INCREMENT  
END
1
  • 2
    There are many examples on SO of using tally tables to populate date table? Did you try to search anything? The clue is to generate number range and use simple INSERT INTO ... SELECT ... FROM (tally) ... WHERE (loop condition) Commented Dec 24, 2015 at 7:29

1 Answer 1

1

Here is one way using Tally table

;WITH e1(n) AS
(
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), -- 10
e2(n) AS (SELECT 1 FROM e1 CROSS JOIN e1 AS b), -- 10*10
e3(n) AS (SELECT 2 FROM e1 CROSS JOIN e2), -- 10*100
e4(n)  as ( SELECT n = ROW_NUMBER() OVER (ORDER BY n) FROM e3)
SELECT n,
       Dateadd(D, n, @TO_DATE)
FROM   e4
WHERE  N <= @DIFFERENCE
       AND N%@INCREMENT = 0 

For more info on Generate a set or sequence without loops

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

Comments

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.