tags:

views:

185

answers:

3

I have two tables that are indirectly related by another table

TableA - ID, SomeFieldA

TableB - ID, SomeFieldB

TableAB - IDA, IDB, SomeFieldAB

I have to generate data from the ground up. So I've put some data in TableA, and I've put some data in TableB. The problem is, I need to insert data into TableAB now, and I don't know how to generate a script that will do all the permutations of TableA and TableB together.

For instance:

Table A has two records:

1, 'A'

2, 'AA'

Table B has two records:

3, 'B'

4, 'B'

I want to insert the following data into TableAB:

1, 3, 'first perm'

1, 4, 'second perm'

2, 3, 'third perm'

2, 4, 'fourth perm'

What's the easiest way to do this?

A: 
 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

DVK
Thanks, I knew it was something easy, I just was trying to JOIN and I was just making it too complicated.
Joseph
Never use that syntax! Maintainers won't know if you indtended a cross join or not. You should always use the explict joins especially when doing cross joins. Very bad practice to use implicit joins.
HLGEM
I'm used to TSQL way of doing things, not ANSI syntax... but I agree it's a valid concern.
DVK
A: 

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.

casperOne
implicit joins, bad - select * bad. Two poor practices in one piece of code, very bad.
HLGEM
+5  A: 

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
KM