Printing Fibonacci Series in SQL
Part - 25
--*********************************************************
-- 25 - Printing Fibonacci Series in SQL - While Loop - Recursive CTE
--********************************************************
Click here for you tube video answer:
Scripts Used:
--*********************************************************************************
-- 25 - Fibonacci Series using SQL
--*********************************************************************************
-- Method 1 (Using While Loop):
DECLARE @ID1 INT = 0, @ID2 INT = 1, @ID3 INT, @Counter INT = 1
PRINT 0
PRINT 1
WHILE (@Counter <11)
BEGIN
SET @ID3 = @ID1+@ID2
PRINT @ID3
SET @ID1 = @ID2
SET @ID2 = @ID3
SET @Counter = @Counter + 1
END
-- Method 2 (Using Recursive CTE):
WITH CTE_Fibonacci (ID1, ID2, Counter)
AS
(SELECT 0 AS ID1, 1 AS ID1, 1 AS Counter --> Anchor query
UNION ALL
SELECT ID2, ID2+ID1, Counter+1 FROM CTE_Fibonacci
WHERE Counter < 12
)
--SELECT * FROM CTE_Fibonacci
SELECT DISTINCT STUFF((SELECT ', ' + CAST(ID1 AS VARCHAR(10)) FROM CTE_Fibonacci FOR XML PATH ('')), 1, 2, '')
AS fibonacci_series FROM CTE_Fibonacci
--SELECT STRING_AGG(ID1, ', ') within group (order by ID1) as fibonacci_series FROM CTE_Fibonacci