views:

3130

answers:

4

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 (?,?,?)

Any ideas if it is possible?

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

marc_s
the valA, valB, valC is from different tables...
+2  A: 
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 . . .
Binary Worrier
ok..great...i'm using this in java, so if colC is getting the values frm a method (eg: method())?
Sorry, I don't do Java
Binary Worrier
A: 

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

lexx
+5  A: 

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 ...)
Andomar
+1 - great response - thanks ! You learn something new every day....
marc_s