Let us say you want to execute multiple sql server scripts multiple times inside your script. I could be updating a table or initializing a table. Well there could be multiple ways to do this such as using cursor, a while loop or even pressing F5 on your key board to the number of time you want to execute the query. My favorite way of doing this is executing a batch statement using GO (number).
Let’s see this in action:
First I will be creating a temp table to demonstrate this there is
CREATE TABLE #testTable( Val int, [Date] datetime ); |
There is nothing fancy about this step of course. Let’s next create a variable and initialize our temp table with the variable and today’s date and time. But Notice there is number 5 after GO with is to tell the server to execute the batch 5 times. After exacting the statement we should have 5 more rows in the table.
---------------Batch Execute DECLARE @testVar INT = 1; INSERT INTO #testTable (Val, [Date]) SELECT @testVar Val, getdate() [Date]; GO 5 |
Querying the table indicate the above statement were executed 5 times indeed.
SELECT Val, [Date] FROM #testTable; GO |