SQL 2000
I have never done loops or variables in SQL, but I think I need to for my current problem. Any help on the syntax would be greatly appreciated!
I need to populate a table with ranges of numbers. My table will have only 2 columns… “from” and “to” values, and should have no gaps between the rows.
Final Table example…
From To
120015 120019
120020 180039
180040 200029
200030 999999
The raw data contains only the “from” value…
From
120015
120020
180040
200030
My thought is that I should be able to loop through this table in descending order, calculate and save the “From -1” value and update it into the “To” value of the next row.
So, here is the logic I think I need. How would I do this in SQL? I won’t know how many rows I have ahead of time.
Set Variable = 999999 (for highest value row)
While there are rows…
Read Raw Data file
Insert into final table (From, Variable)
Read Next Row
Data would look like this in the loop…
First pass
From = 200030
Insert into Final Table (From, Variable) (200030, 999999)
Set Variable = From -1 (200029)
Second pass
From = 180040
Insert into Final Table (From, Variable) (180040, 200029)
Set Variable = From -1 (180039)
Third pass
From = 120020
Insert into Final Table (From, Variable) (120020, 180039)
Set Variable = From -1 (120019)
Etc.
So my final table (descending, as input) would be
200030, 999999
180040, 200029
120020, 180039
120015, 120019
Thank you!
~Toni
I have never done loops or variables in SQL, but I think I need to for my current problem. Any help on the syntax would be greatly appreciated!
I need to populate a table with ranges of numbers. My table will have only 2 columns… “from” and “to” values, and should have no gaps between the rows.
Final Table example…
From To
120015 120019
120020 180039
180040 200029
200030 999999
The raw data contains only the “from” value…
From
120015
120020
180040
200030
My thought is that I should be able to loop through this table in descending order, calculate and save the “From -1” value and update it into the “To” value of the next row.
So, here is the logic I think I need. How would I do this in SQL? I won’t know how many rows I have ahead of time.
Set Variable = 999999 (for highest value row)
While there are rows…
Read Raw Data file
Insert into final table (From, Variable)
Read Next Row
Data would look like this in the loop…
First pass
From = 200030
Insert into Final Table (From, Variable) (200030, 999999)
Set Variable = From -1 (200029)
Second pass
From = 180040
Insert into Final Table (From, Variable) (180040, 200029)
Set Variable = From -1 (180039)
Third pass
From = 120020
Insert into Final Table (From, Variable) (120020, 180039)
Set Variable = From -1 (120019)
Etc.
So my final table (descending, as input) would be
200030, 999999
180040, 200029
120020, 180039
120015, 120019
Thank you!
~Toni