SQL Server: INSERT INTO from Multiple Tables without Relationship

advertisements

Table 1:

NAME
------
Clara
Bob

Table 2:

NUMBER
--------
555-1111
555-2222
555-3333

and now I want to insert data in table 3 which shows me information like:

NAME    NUMBER
----------------
Clara   555-1111
Clara   555-2222
Clara   555-3333
Bob     555-1111
Bob     555-2222
Bob     555-3333

I know this can be done using two different SQL queries, but I want to do this in single query. I don't have any relationship between table1 and table2. How can I insert these records in a single insert statement, without using WHILE loop.


Use cross join to generate the data:

select t1.name, t2.number
from t1 cross join t2;

You can use insert or select into to put the results into another table:

insert into t3(name, number)
    select t1.name, t2.number
    from t1 cross join t2;

Ironically, I can't think of a reasonable way of doing this with exactly two queries.