Link to home
Start Free TrialLog in
Avatar of damixa
damixaFlag for Denmark

asked on

sql query to insert the fibonacci sequence into a table

I need an insert statement to insert the fibonacci sequence into a table. Lets think for a moment that the table has two fields

fibid - is an integer, identity field
fibnum is where the fibonacci sequence should go.

so it will be something like this

fibid(1,2,3,4,5)
fibnum(1,2,3,5,8)

etc

lets say populate 200 records

thanks,
Vinnie
Avatar of Surendra Nath
Surendra Nath
Flag of India image

There are many ways to solve this problem, with different performances.....

But for a novice and easy to understand the below is the best approach

Step 1 : Create a table fibonacci with the required fields
step 2 : create a loop
Step 3 : caliculate the current fibonacci number
step 4: Store it in the table

DECLARE @T TABLE
(
fbid BIGINT IDENTITY(1,1)
,Fib BIGINT
)

DECLARE @FibonacciCurrent BIGINT
DECLARE @FibonacciPast BIGINT
DECLARE @Temp BIGINT
DECLARE @Counter BIGINT
SET @FibonacciCurrent = 1
SET @FibonacciPast = 1
WHILE (@Counter < 200)
BEGIN
   INSERT INTO @t (fib)
   SELECT @FibonacciCurrent

   SET @temp = @FibonacciCurrent  
   SET @FibonacciCurrent = @FibonacciCurrent + @FibonacciPast
   SET @FibonacciPast = @temp

   SET @Counter = @counter + 1
END

SELECT * FROM @T

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Sharath S
Sharath S
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial