Skip to content
Advertisement

Insert into sql server table, using subquery returning more than 1 value

I have the following tables

table1

enter image description here

table2

enter image description here

table3

enter image description here

I want for every id in table2 where condition is true, to insert 2 rows in table1. The rows should have the table2.id and table3.id ( for all ids in table3)

Here is my script so far.

INSERT INTO table1 (wid, w_check_id)
SELECT (SELECT w.id FROM table2 w WITH(NOLOCK) WHERE w.category_code IN ('004','001')),
       id
FROM table3 WITH(NOLOCK)

The expected result should be something like this:

table1

id | w_id | w_check_id

1 | 32098 | 1

2 | 32098 | 2

3 | 82459 | 1

4 | 82459 | 2

Advertisement

Answer

The rows should have the table2.id and all ids in table3 sounds like you need a cross join as:

Insert into  @T1 (wid,w_check_id)
SELECT w.id,T3.Id
FROM @T2 w 
cross JOin @T3 T3
WHERE w.wallet_category_code IN ('004','001')
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement