The Light
The Light

Reputation: 27021

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?

Upvotes: 2

Views: 341

Answers (3)

Taryn
Taryn

Reputation: 247880

You will use an INSERT INTO SELECT FROM

INSERT INTO Countries (ID)
SELECT countryID
FROM @countries

Upvotes: 2

Curtis
Curtis

Reputation: 103428

insert into Countries (ID)
SELECT CountryId FROM @countries

http://www.sqlteam.com/article/using-select-to-insert-records

Upvotes: 3

Andomar
Andomar

Reputation: 238296

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

insert  Countries 
        (ID) 
select  countryId 
from    @countries

Upvotes: 6

Related Questions