Technical Article

T-SQL implementation of FizzBuzz

,

FizzBuzz has long been used as an interview screening device for computer programmers. The task is as follows: Print 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”.

For what it's worth, here I present my own T-SQL implementation of FizzBuzz consisting of a single SELECT statement.

Feel free to reply with your own variation in the discussion forum for this post.

SELECT  
   CASE WHEN n % 3 = 0 AND n % 5 = 0 THEN 'FizzBuzz'
   WHEN n % 3 = 0 THEN 'Fizz'
   WHEN n % 5 = 0 THEN 'Buzz'
   ELSE CAST(n AS VARCHAR(9))
   END AS p
FROM
   ( SELECT ROW_NUMBER() OVER ( ORDER BY id ) AS n
   FROM sys.sysobjects ) x
WHERE n <= 100
ORDER BY n;

Rate

4.86 (7)

You rated this post out of 5. Change rating

Share

Share

Rate

4.86 (7)

You rated this post out of 5. Change rating