1

How can I insert multiple rows from another table with multiple rows without using a cursor?

Example:

Let's say I have three tables:

  1. Customers (CustomerId, Name)
  2. Gifts (GifId, GiftName)
  3. 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.

0

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This is what i was looking for. I know it had to be some better way than using cursors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.