Wednesday, March 25, 2015

Fibonacci series with T-SQL




DECLARE @intStart       INT            = 0
DECLARE @intEnd         INT            = 1000 --change this to what ever fibonacci series you want. Make sure the results fit in integer datatype. if not change them to BIGINT or DECIMAL/FLOAT
DECLARE @vchFinalOutPut VARCHAR(MAX)   = ' '
DECLARE @intResult      INT            = 0
DECLARE @intNextValue   INT            = 1

WHILE @intStart < @intEnd
BEGIN
   SET @vchFinalOutPut = @vchFinalOutPut + ',' + LTRIM(RTRIM(STR(@intStart)))
   SET @intResult = @intStart --Store the start value
   SET @intStart = @intNextValue
   SET @intNextValue = @intResult + @intNextValue --Add previous and current value
END


PRINT LTRIM(RTRIM(STUFF(@vchFinalOutPut,PATINDEX('%,%', @vchFinalOutPut),1,'')))