Pinal Dave posted yesterday about how to solve the Fizz Buzz problem using T-SQL.
Definition of FizzBuzz Puzzle : Write a program 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”.
His solution works, but he is using procedural logic. Some of the biggest causes of performance problems in SQL Server are caused by application developers who try to use procedural logic instead of using the set-based logic that databases are meant for.
Here is how to solve the FizzBuzz problem using set-based logic in T-SQL:
WITH Numbers(Number) AS ( SELECT 1 UNION ALL SELECT Number + 1 FROM Numbers WHERE Number < 100 ) SELECT CASE WHEN Number % 3 = 0 AND Number % 5 = 0 THEN 'FizBuzz' WHEN Number % 3 = 0 THEN 'Fizz' WHEN Number % 5 = 0 THEN 'Buzz' ELSE CONVERT(VARCHAR(3), Number) END FROM Numbers ORDER BY Number






