Monday, February 10, 2014

SQL - WHILE Loops

Refer Source : SQL - WHILE Loops

******************************
The Basic Syntax of WHILE:
******************************
exam.1  
DECLARE @Counter INT
SET @Counter = 1

WHILE @Counter<=10
BEGIN
PRINT @Count
SET @Count = @Count + 1
END

exam.2:Using SELECT Statement in a Loop.
DECLARE @Counter INT
DECLARE @MaxOscars INT
DECLARE @NumFilms INT
SET @Counter = 0
SET @MaxOscars = (SELECT MAX(FilmOscarWins) FROM tblFilm)

WHILE @Counter<=@MaxOscars
BEGIN
SET @NumFilms = SELECT COUNT(*) FROM tblFilm) FilmOscarWins = @Counter)

--IF @NumFilms = 0 BREAK

PRINT CAST(@NumFilms AS VARCHAR(3)) +  + 'fILM HAVE WON' + CAST(@Counter AS VARCHAR(2)+ + 'Oscars' 

SET @Count = @Count + 1
--(if the above is commented then @count is always 0, it will be end less loop)
--make sure the condition to be false , to break it.

END

(Can do this in group by clause, but the records showing no films having 9 oscars and 9 oscars,Refer Video.)

******************************
Using BREAK to Exit a Loop:In the above:IF @NumFilms = 0 BREAK
******************************

This will not print unlike the 11 Oscars.Refer Video.

******************************
How to Stop an Endless Loop:--make sure the condition to be false
******************************
******************************
Using Loops with Cursors:covered in Cursor post.
******************************

No comments:

Post a Comment