Search code examples
sql-server

Insert all combinations of two tables in intermediate table in SQL Server


My situation

I'm making a site where people can reserve meeting rooms. On the reservation form for a meeting room, I've some optional field sets like below:

ID Name
1 Catering
2 Coffee break
3 Drinks

Here are some example meeting rooms:

ID Name Location
1 Dog Brussel
2 Cat Antwerpen
3 Chicken Brugge
4 Cow Gent

I'm using Microsoft SQL server 2016.

Database structure

  • The fieldsets from the first code block stands inside my database in the table reservationFieldsets.
  • The meeting rooms stands in the meetingRooms table.
  • There is an intermediate table named meetingRoomsReservationFieldsets.

Question

Now I'll fill meetingRoomsReservationFieldsets with all rooms and all the fieldsets like below:

RoomID FieldsetID
1 1
2 1
3 1
4 1
1 2
2 2
3 2
4 2
1 3
2 3
3 3
4 3

I've tried

I've tried to do it manually but there are a lot of rooms and too much to do that manual.


Solution

  • I've found it by the comments on the question. I use this code:

    INSERT INTO meetingRoomsReservationFieldsets
    SELECT meetingRooms.id, reservationFieldsets.id
    FROM reservationFieldsets
    CROSS JOIN meetingRooms