view raw
Zahid Zahid - 9 months ago 52
SQL Question

Write Query without using loop

Write a program using SQL that prints the numbers from 1 to 100.

But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”

DECLARE @counter INT
SET @counter = 1
WHILE @counter < 101
SET @output = ''
IF @counter % 3 = 0
SET @output = 'Fizz'
IF @counter % 5 = 0
SET @output = @output + 'Buzz'
IF @output = ''
SET @output = @counter
PRINT @output
SET @counter = @counter + 1

This gives desired output. But,I am asked not to use loop,Is it possible to do this any other way? How about using CTE?

;With cte(n)--this is a recursive cte
select  1--anchor part
union all
select n+1
from cte where n<100 --recursive part,when this completes we have a temp table of 100 numbers
case when n%3=0 and n%5=0 then 'Fizz Buzz'
     when n%5=0 then 'Buzz'
     when n%3=0 then 'Fiz'
     else cast(n as varchar(4)) end
from cte

From that table ,we are using case to calculate modulo.Read out below articles on why numbers tables are usefull and how they can replace loops..

1. 2.