Little SQL Server Tricks: Creating a Range of Numbers

Some tasks I do in SQL Server would be much simpler if I could get a sequence or a range of numbers. I could create users#1 to user#1000 without any programming – just by using plain old SQL. PostgreSQL offers the generate_series function for such use cases. Unfortunately, there is nothing comparable in SQL Server. All you can find on Google are solutions that are complicated, long and impossible to remember.

The one exception I found was from johnqflorida in his answer in the SQL Server forums. His solution is short and works with large ranges. You can use this query to get the numbers from 1 to 100’000 – each number in its own row:

With a little modification, you can get any range you need (50 to 250):

To create Users with a number in their name, you can combine the range from above with your INSERT statement:

This approach gives me up to 16 million values before SQL Server runs into an out of memory exception. I may never need such a big range, but it is great to finally have a solution that can produce a large range of numbers without falling back to writing my own procedures or complicated statements.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.