Collections:
WHILE ... Loops in SQL Server Transact-SQL
How to execute statements in loops in SQL Server Transact-SQL? How to use WHILE ... loops?
✍: FYIcenter.com
You can use WHILE ... statements to execute statements in loops
in Transact-SQL using these syntaxes:
-- Loop with a single statement
WHILE condition statement
-- Loop with a statement block
WHILE condition
-- statement_block
BEGIN
... statements ...
END
When a WHILE ... loop statement is executed, the system will:
Here is an example on how to use WHILE ... loop statements:
DECLARE @count INT = 1, @sum INT = 0;
WHILE @count <= 10
BEGIN
SET @sum = @sum + @count;
SET @count = @count+1;
END
PRINT 'Sum of 1 to 10: ' + CAST(@sum AS CHAR);
Here is another example of WHILE ... loop statement:
-- Counting number of days in 2000
DECLARE @date DATETIME;
DECLARE @count INT;
SET @date = '2000-01-01';
SET @count = 0;
WHILE DATEPART(YEAR, @date) = 2000
BEGIN
SET @count = @count + 1;
SET @date = DATEADD(DAY, 1, @date);
END
SELECT @count;
366
-- 2000 is a leap year!
⇒ BREAK of Loop Statement in SQL Server Transact-SQL
⇐ "IF ... ELSE IF ..." Statement Structures in SQL Server
⇑ Conditional Statements and Loops in SQL Server in SQL Server Transact-SQL
2017-01-11, 4977🔥, 0💬
Popular Posts:
How To Drop an Index in Oracle? If you don't need an existing index any more, you should delete it w...
What Happens to Your Transactions When ERROR 1213 Occurred in MySQL? If your transaction receives th...
How to continue to the next iteration of a WHILE loop in SQL Server Transact-SQL? How to use CONTINU...
What Happens If the Imported Table Already Exists in Oracle? If the import process tries to import a...
What Is Program Global Area (PGA) in Oracle? A Program Global Area (PGA) is a memory buffer that is ...