FizzBuzz In SQL

This has been done many times before by many other people, but I set this challenge to a friend of mine who was interested in programming, and then realised that I had no solution. So I spent the train journey home writing my effort below. Like a lot of things in computer programming, there’s more than one correct way, but many more incorrect ways! I like this way because it’s quite small and readable.


DECLARE @COUNT TINYINT = 1
DECLARE @FizzBuzz VARCHAR(8)

WHILE @COUNT < 101
BEGIN
SELECT @FizzBuzz = CASE
WHEN @COUNT % 3 = 0
AND @COUNT % 5 = 0
THEN 'FizzBuzz'
WHEN @COUNT % 3 = 0
THEN 'Fizz'
WHEN @COUNT % 5 = 0
THEN 'Buzz'
ELSE CAST(@Count AS VARCHAR(3))
END

PRINT @FizzBuzz

SELECT @COUNT = @COUNT + 1
END

Author: Richie Lee

Full time computer guy, part time runner. Full time Dad, part time blogger. Pokémon Nut. Writer of fractured sentences. Maker of the best damn macaroni cheese you've ever tasted.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s