I’ve tried to figure out how this SQL query generates a sequence of numbers, and I still don’t have a clue.
Digits Table
digit
--------
0
1
2
3
4
5
6
7
8
9
SELECT D3.digit * 100 + D2.digit * 10 + D1.digit + 1 AS n
FROM dbo.Digits as D1
CROSS JOIN dbo.Digits as D2
CROSS JOIN dbo.Digits AS D3
ORDERY BY n;
The Query Result…
n
------
1
2
3
4
5
...
998
999
1000
How does it work?
CROSS JOIN is much like an
INNER JOIN MYTable on 1 = 1, resulting in the Cartesian Product of your Input SetsBasically, for each record on the left, it joins for each record on the right.
In the case of a 10-digit source table, the first cross join results in 100 records.
In the case of a second cross join to the same 10-digit source table, you get all 100 previous records again, for each record in the source table, resulting in 1000 records.
Your resulting table would look like this, if you your Select Statement was “Select * …” Order by …
If you take those values in the table above and concatenate them (then add one) you get consecutive numbers.
Obviously, the author is not concatenating. However, he’s doing the mathematical equivalent.
Ultimately, the author devised a strange way to provide a listing of numbers from 1 to 1000.