How To Stop a Loop Early with BREAK Statements in MS SQL Server?
Submitted by: AdministratorIf you want to stop a WHILE loop early, you can use the BREAK statement in the loop statement block.
The tutorial exercise below shows you how to use a BREAK statement to stop a WHILE loop early:
-- Counting number of days in 2000
DECLARE @date DATETIME;
DECLARE @count INT;
SET @date = '2000-01-01';
SET @count = 0;
WHILE 1=1 BEGIN
IF DATEPART(YEAR, @date) > 2000 BREAK;
SET @count = @count + 1;
SET @date = DATEADD(DAY, 1, @date);
END
SELECT @count;
366
-- 2000 is a leap year!
Submitted by: Administrator
The tutorial exercise below shows you how to use a BREAK statement to stop a WHILE loop early:
-- Counting number of days in 2000
DECLARE @date DATETIME;
DECLARE @count INT;
SET @date = '2000-01-01';
SET @count = 0;
WHILE 1=1 BEGIN
IF DATEPART(YEAR, @date) > 2000 BREAK;
SET @count = @count + 1;
SET @date = DATEADD(DAY, 1, @date);
END
SELECT @count;
366
-- 2000 is a leap year!
Submitted by: Administrator
Read Online MS SQL Server Job Interview Questions And Answers
Top MS SQL Server Questions
☺ | How To Execute the Cursor Queries with "OPEN" Statements? |
☺ | How To Create a View on an Existing Table in MS SQL Server? |
☺ | What Are the Advantages of Passing Name-Value Pairs as Parameters? |
☺ | How to download and install the scaled-down database AdventureWorksLT? |
☺ | PHP MSSQL - How To Display a Past Time in Days, Hours and Minutes? |
Top Databases Programming Categories
☺ | RDBMS Interview Questions. |
☺ | SQL Interview Questions. |
☺ | SSRS Interview Questions. |
☺ | Database Administrator (DBA) Interview Questions. |
☺ | Sybase Interview Questions. |