sqlsql-server

Creating multiple numbered rows in a table Sql Server


Desc I have table name: tableName and column name: columnName

Problem I need to create 450 lines and number them from 1 to 450.

I tried:

For(int i=1; i<451;i++)
{
  INSERT INTO tableName (columnName) VALUES i
}

for. exp.

IdP

1

2

3

...

Error: Could not find procedure

I don't know what procedure to use.


Solution

  • In SQL Server, you can use recursive cte instead :

    with cte as (
         select 1 as start, 450 as loop_end
         union all
         select c.start + 1, loop_end
         from cte c
         where c.start < loop_end
    )
    INSERT INTO tableName (columnName)
       select c.start
       from cte c
       option (maxrecursion 0);