Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 620
pablo brandenburg Avatar asked Oct 27 '25 09:10

pablo brandenburg


1 Answers

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.

like image 186
Gordon Linoff Avatar answered Oct 28 '25 22:10

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!