0

How to run a while loop to run a dynamic query in SQL?

Declare @var1 nvarchar(max)
Declare @var2 nvarchar(max)
Declare @var3 nvarchar(max)

While loop ( @var1, @var2, @var3 .... )
 Begin  
     insert into TableA
     exec (@var1) .. - in the loop logic
 End
8
  • You may refer while loops in sql-server Commented Apr 11, 2019 at 5:45
  • Yeah , but passing the variable & running the exec var1 .. exec @var2 in the sequence .. Commented Apr 11, 2019 at 5:46
  • This is a dynamic query execution, not just while loop .. I need to fetch each variables to the exec syntax Commented Apr 11, 2019 at 5:47
  • do you want to iterate through the list of variables? Commented Apr 11, 2019 at 5:51
  • Yes please.. fetch each variable & pass it to the exec syntax inside the loop Commented Apr 11, 2019 at 5:52

1 Answer 1

1

If I understood well, you wan to use a loop to execute a set of dynamic SQL queries. Then you need to use a table to iterate between them, Im using a variable table, but you can use a temp table if you prefer

DECLARE @Vars TABLE([ID] NOT NULL IDENTITY, [Var] NVARCHAR(MAX))
/*
INSERT Values to @Vars
*/
DECLARE @ID INT, @Var NVARCHAR(MAX)
WHILE EXISTS (SELECT 1 FROM @Vars)
BEGIN
    SELECT TOP 1 @ID = [ID], @Var = [Var] FROM @Vars ORDER BY [ID]

    INSERT TableA
    EXEC(@Var)

    DELETE @Vars WHERE [ID] = @ID
END
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.