Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Numbers table explanation

Status
Not open for further replies.

pbsadmin

Technical User
Aug 19, 2009
18
0
0
US
Hi,

I'm new to T-SQL and programming in general, and had a question regarding some code used to generate a numbers table. I realize there is more than one way to do this, I am curious as to what the statement

SELECT n + @rc does. To me it appears it is simply placing the contents of the @rc variable into the single column table, but I'm not sure.

When I change the statement SET @rc = @rc * 2 to
SET @rc = @rc * 4 I get the following results

Code:
n
-----------
1
2

n
-----------
1
2
5
6

n
-----------
1
2
5
6
17
18
21
22

I'm not quite understanding why the table contains the numbers 1, 2, 3 ,4

n
-----------
1
2

n
-----------
1
2
3
4

when to me it appears like the table should contain

n
------------
1
2
4
8

etc

help would be appreciated, thanks

example with "2" below

Code:
IF OBJECT_ID('dbo.Nums', 'U') IS NOT NULL

DROP TABLE dbo.Nums;

CREATE TABLE dbo.Nums(n INT NOT NULL PRIMARY KEY);

DECLARE @max AS INT, @rc AS INT;

SET @max = 100;
SET @rc = 1;

INSERT INTO dbo.Nums(n) VALUES(1);

WHILE @rc * 2 <= @max
	
	BEGIN

		INSERT INTO dbo.Nums(n)
		SELECT n + @rc
		
		FROM dbo.Nums;                   
		
		SELECT n                       
     	        FROM dbo.Nums                 
	    
	        SET @rc = @rc * 2;                  

	END


truncated results
Code:
n
-----------
1
2

n
-----------
1
2
3
4

n
-----------
1
2
3
4
5
6
7
8

n
-----------
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
The odd number is coming from the loop "SELECT n + @rc FROM dbo.Nums"
The first row to go into the table is a insert values of 1
When you select n from dbo.nums it will pick the first row where the value will always be one

SET @rc = 1
INSERT INTO dbo.Nums(n) VALUES(1)
First row of the table will be 1

First pass of the loop inserts n=1 plus @rc=1
You now have 2 rows 1,2
You reset @rc to @rc * 2 (1 * 2) = 2

Next pass of the loop inserts n=1 plus @rc=2
You now have 3 rows 1,2,3

You reset @rc to @rc * 2 (2 * 2) = 4
You now have 4 rows 1,2,3,4

Change
INSERT INTO dbo.Nums(n) SELECT n + @rc FROM dbo.Nums
to
INSERT INTO dbo.Nums(n) SELECT MAX(n) * 2 FROM dbo.Nums and do away the @rc variable completely





 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top