Search code examples
sqlsql-servert-sqlcursor

How to run an Insert statement for each item in the SQL Table?


I have a table variable as below:

declare @countries table (countryId int)

which has 5 records in it.

I'd need to write a separate insert statement for each countryId in the list, like:

insert into Countries (ID) VALUES (countryId)

How would that be possible without using a cursor?

Is there any simpler way?


Solution

  • You could use insert ... select instead of insert ... values:

    insert  Countries 
            (ID) 
    select  countryId 
    from    @countries