SQL: INSERT INTO…VALUES..SELECT

后端 未结 4 1211
一向
一向 2021-01-01 13:23

How do i write INSERT statement if i get the values of colA from TableX, colB from TableY and colC from TableZ?

eg: INSERT INTO TableA (colA, colB, colC) VALUES (?,?

相关标签:
4条回答
  • 2021-01-01 13:40

    You will need to join the tables that you want to make the selection from.

    Here is a resource on SQL joins:

    www.w3schools.com/sql/sql_join.asp

    You also might want to check out this free PDF book from the guys at www.simple-talk.com that covers SQL basics:

    SQL Server Crib Sheet Compendium

    0 讨论(0)
  • 2021-01-01 13:53

    In response to marc_s's answer, you can query from unrelated tables in a since select like:

    INSERT INTO TableA
        (colA, colB, colC)
    SELECT
        (SELECT valA FROM TableX WHERE ...),
        (SELECT valB FROM TableY WHERE ...),
        (SELECT valC FROM TableZ WHERE ...)
    
    0 讨论(0)
  • 2021-01-01 13:56
    Insert into TableA (ColA, ColB, ColC) . . .
    

    Must be the column names as the are in Table A. There's nothing wrong with

    Insert into TableA (ColA, ColB, ColC) . . .
    Select TableX.Col1, TableY.Col1, TableZ.Col5 
    From TableX, TableY, TableZ
    Where . . . 
    
    0 讨论(0)
  • 2021-01-01 14:02
    INSERT INTO TableA(colA, colB, colC)
      SELECT TableX.valA, TableY.valB, TableZ.valC
        FROM TableX
       INNER JOIN TableY ON :......
       INNER JOIN TableZ ON ........
    

    Of course, TableX, TableY and TAbleZ might also be related in some other way (not INNER JOIN).

    If you cannot find any relation between the tables AT ALL, you could also do three separate

    SELECT @value1 = valA FROM TableX WHERE ......
    SELECT @value2 = valB FROM TableY WHERE ......
    SELECT @value3 = valC FROM TableZ WHERE ......
    

    and then an insert like this:

    INSERT INTO TableA(colA, colB, colC)
                 VALUES(@value1, @value2, @value3)
    

    That's the ultimate last resort, you can can't express everything in a single SELECT statement.

    Marc

    0 讨论(0)
提交回复
热议问题