Results 1 to 4 of 4

Thread: [RESOLVED] Insert into from 2 tables

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Nov 2001
    Location
    Mass USA
    Posts
    1,674

    Resolved [RESOLVED] Insert into from 2 tables

    Hey,

    I got 2 tables each with their own key

    Table 1
    Key1

    Table2
    Key2

    I need a SQL statement that will insert into Table3 Key1 as primary and Key2 as foreign.

    What would be the best way to do that?

    Table3 end result would look like:

    Key1 | Key2
    1 | 1
    2 | 1
    3 | 1
    1 | 2
    2 | 2
    3 | 2

    Thanks for any direction.

  2. #2
    A SQL Server fool GaryMazzone's Avatar
    Join Date
    Aug 2005
    Location
    Dover,NH
    Posts
    7,493

    Re: Insert into from 2 tables

    I don't think you can do what you just described. If you want to insert Key1 as a primary key you can't insert that key twice in your example 1,1 and 1,2. If you want you can create a combination PK based on Key1 and Key2 and have both columns FKed to their respective tables...... Or add a third column as the PK and then the other two as columns with FKs to the repective tables.

    Is it that you want every row in table1 to relate to every row in table 2?
    Sometimes the Programmer
    Sometimes the DBA

    Mazz1

  3. #3
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Insert into from 2 tables

    Primary keys can't have duplicate values. So the Table3 result you posted won't be possible if Key1 is declared as Primary Key in Table3.

    Looking from the result you posted, I assume you want the Cartesian Product (cross join) of Key1 (from Table1) and Key2 (from Table2). In that case this query should work for you:
    Code:
    INSERT INTO Table3 (Key1, Key2)
    SELECT Table1.Key1, Table2.Key2 From Table1, Table2
    ORDER BY Table2.Key2, Table1.Key1
    Pradeep
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  4. #4

    Thread Starter
    Frenzied Member
    Join Date
    Nov 2001
    Location
    Mass USA
    Posts
    1,674

    Re: Insert into from 2 tables

    Thats exactly what I needed Pradeep. Thank both of you for your time.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width