I've seen the following used to return a list of numbers
SELECT TOP (SELECT MAX(Quantity) FROM @d)
rn = ROW_NUMBER() OVER (ORDER BY object_id)
FROM sys.all_columns
ORDER BY object_id
if the max quantity is 5 then I assume the above returns:
rn
1
2
3
4
5
Is there a more elegant, or even canonical, approach within T-SQL to return this list of numbers?
7条答案
按热度按时间wfypjpf41#
You can do:
This is tolerable when the number is 5, but not 50 or 5000. When you need more you can do things like use a CTE to build up a set of numbers to then cross join to explode the set (you can see a couple of examples here, under Inline 1 / Inline 2 ).
Or you can build a table of Numbers, let's say you may need 5 or you may need a million:
Then when you want some numbers you just say:
Obviously using sys.all_columns or any built-in object with sufficient rows avoids the up-front step of creating a Numbers table (which many people object to, for some reason, anyway).
Now, it would be really nice if there were a more elegant way to do this, wouldn't it? You won't see it in any current version but there's a chance we'll see it in a future version. Please go vote (and more importantly, comment on your use case) here:
http://connect.microsoft.com/SQLServer/feedback/details/258733/add-a-built-in-table-of-numbers
cotxawn72#
Definitely not the most elegant, but probably the fastest way for larger sequences:
No temp tables, no table reads, and you can define your maximum yourself.
You can copy-paste the ready-to-use function from here
wnavrhmk3#
I've used something like this in the past -- though it only works up to 100 or so:
e37o9pze4#
First create a table of numbers 0 - 9
Then you can produce the following cross join to count from 1 to 100:
To count from 1 to 1000, you simply need to add an additional cross join:
To count from 1 to x (where x <= 1000)::
bq3bfh9z5#
Modify the Top value as required:
e.g. A dropdown list showing a range of NULL, 1 - 30 for a list of years of education.
sgtfey8w6#
If you only wanted your output to contain a running number as an additional column, the following would work as well:
ocebsuys7#
if you are on sql 2022 or azure where
string_split
supportsordinal
, you can do this for a million numbers for example: