Reputation: 515
How can I insert multiple rows from another table with multiple rows without using a cursor?
Example:
Let's say I have three tables:
Customers
(CustomerId
, Name
)Gifts
(GifId
, GiftName
)GiftsToCustomers
(GiftId
, CustomerId
)The table customers and gifts can contain more then one row.
Now let's say I have 3 gifts in the table Gifts
and I want to give this to all my customers.
Is there a way I can do this without using an cursor/loop through either the Customers
or Gifts
table?
I'm not looking for something like
insert into GiftsToCustomers
Select GiftId, @CustomerId
from Gifts
Where I have to do it on every row in customers/gifts.
Upvotes: 1
Views: 133
Reputation: 312267
A cross join should do the trick - you can use it to match each row in gifts
with each row in custmers
:
INSERT INTO GiftsToCustomers (GiftId, CustomerId)
SELECT GiftId, CustomerId
FROM Gifts
CROSS JOIN Customers
Upvotes: 3