September 25, 2009 by Mike Hillwig
I recall reading Brent Ozar’s post on questions to ask DBAs in an interview.
Unable to sleep last night, I was trying to solve the Fizzbuzz problem in my head. I knew it could be done with T-SQL, but I hadn’t given it too much thought.
I’m lying in bed mapping out the code in my head. First, I would create a table containing a primary key of integers from 1 to 100. Then I would run several update statements to set the second column to what would be displayed.
I fell asleep thinking I had solved the problem fairly well. This morning, I sat down in front of my computer at work, wanting to test my plan. Suddenly, it hit me. I had made the solution much more complicated than it needed to be.
Dear readers, I give you my solution in twelve lines of code.
declare @i int
select @i = 1
while @i <= 100
WHEN @i %3 = 0 AND @i % 5 = 0 THEN ‘FIZZBUZZ’
WHEN @i % 3 = 0 THEN ‘FIZZ’
WHEN @i % 5 = 0 THEN ‘BUZZ’
ELSE CAST(@i AS NVARCHAR(30))
select @i = @i + 1
I’m always looking for a better way of doing things. While this is a much more elegant solution than I had originally found, I’m wondering if it can be any simpler.
Category SQLServerPedia Syndication | Tags: