使用 SQL 编写一个程序,打印 1 到 100 之间的数字。
但是对于三的倍数打印“Fizz”而不是数字,对于五的倍数打印“Buzz”。对于三和五的倍数的数字打印“FizzBuzz”
DECLARE @counter INT
DECLARE @output VARCHAR(8)
SET @counter = 1
WHILE @counter < 101
BEGIN
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
END
这给出了所需的输出。但是,我被要求不要使用循环,是否可以通过其他方式做到这一点?使用 CTE 怎么样?
最佳答案
;With cte(n)--this is a recursive cte
as
(
select 1--anchor part
union all
select n+1
from cte where n<100 --recursive part
)
select
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
从该表中,我们使用大小写来计算模。阅读下面的文章,了解数字表为何有用以及它们如何替换循环。
1.http://dataeducation.com/you-require-a-numbers-table/
2.http://www.sqlservercentral.com/articles/T-SQL/62867/
3.https://dba.stackexchange.com/questions/11506/why-are-numbers-tables-invaluable
关于sql - TSQL - 不使用循环写入 FIZZBUZZ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38841684/