Search code examples
sqlt-sqlsql-server-2017

Insert values into table from a range


I'm trying to do an insert to a table (say table1), where i want to insert a range of numbers after appending a char or int declare?

ex. for Range 1-10

abc1,
abc2,
abc3,
abc4,
.
.
.

any ideas?


Solution

  • I'm fond of recursive CTEs for this purpose:

    with nums as (
          select @rangestart as n
          union all
          select n + 1
          from nums
          where n < @rangeend
         )
    insert into table1(col)
        select 'abc' + cast(nums.n as varchar(255))
        from nums;
    

    If you have more than 100 numbers, you should use the MAXRECURSION option. Also, any numbers table can serve the same purpose.