I have two tables that are indirectly related by another table
TableA - ID, SomeFieldA
TableB - ID, SomeFieldB
TableAB - IDA, IDB, SomeFiel
INSERT TableAB
SELECT A.ID 'IDA', B.ID 'IDB'
, A.SomeFieldA+" "+B.SomeFieldB 'SomeFieldAB'
FROM A, B
A join without any conditions does all the permutations
You can do this:
select
a.*, b.*
from
a, b
This will do a cross join which will give you all possible combinations.
From there, it's simple to use that within the context of an INSERT statement to populate your AB table.
Don't use the ancient join syntax: FROM A, B
, use a proper join:
DECLARE @TableA table (Col1 varchar(5), Col2 varchar(5))
DECLARE @Tableb table (Col1 varchar(5), Col2 varchar(5))
INSERT INTO @TableA VALUES ('a','a')
INSERT INTO @TableA VALUES ('aa','aa')
INSERT INTO @TableB VALUES ('b','b')
INSERT INTO @TableB VALUES ('BB','BB')
SELECT
*
FROM @TableA
CROSS JOIN @TableB
ORDER BY 1
OUTPUT
Col1 Col2 Col1 Col2
----- ----- ----- -----
a a b b
a a BB BB
aa aa b b
aa aa BB BB
(4 row(s) affected)
this will also produce the same result set:
SELECT
*
FROM @TableA
JOIN @TableB ON 1=1
ORDER BY 1