views:

70

answers:

3

How can I update a complete data row by using a data row from another table.

Example:

Table A

ID   |   NAME    |   ...   |
----------------------------
 1   |   Test    |   ...   |
 2   |   Test2   |   ...   |



Table B

ID   |   NAME    |   ...   |
----------------------------
 1   |   Test97  |   ...   |

So I want to copy the content of a single row of Table B to Table A and override existing values. I do not want to name all columns. The contents of table A and B are redundant.

Summarize: I want an equivalent to the following INSERT Statement as an UPDATE Statement:

INSERT INTO destTable 
VALUES  (SELECT * FROM TABLE2)
FROM srcTable 

Any hint, even telling me that its not possible, is very appricated.

+3  A: 

Like so:

UPDATE suppliers  
SET supplier_name = ( SELECT customers.name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id) 
WHERE EXISTS
  ( SELECT customers.name
    FROM customers
    WHERE customers.customer_id = suppliers.supplier_id); 
Ardman
Thanks, but I don't want to name each column. Any other suggestions?
hkda150
If the columns are the same, then I believe you can just do:UPDATE tableA FROM tableB WHERE etc.
Ardman
Can't upvote anymore (value too old to be changed...). Sorry for that. Would like to upvote...
hkda150
No worries. Thanks though :o)
Ardman
+1  A: 

You want to use an Oracle MERGE statement. With this statement, it inserts if a match doesn't exist and updates if it already exists.

Here is a site with an example.

MERGE INTO bonuses b
USING (
  SELECT employee_id, salary, dept_no
  FROM employee
  WHERE dept_no =20) e
ON (b.employee_id = e.employee_id)
WHEN MATCHED THEN
  UPDATE SET b.bonus = e.salary * 0.1
  DELETE WHERE (e.salary < 40000)
WHEN NOT MATCHED THEN
  INSERT (b.employee_id, b.bonus)
  VALUES (e.employee_id, e.salary * 0.05)
  WHERE (e.salary > 40000);
j0rd4n
The only trick to this is that you have to explicitly list your columns in the UPDATE statement which it sounds like you don't want to do.
j0rd4n
+5  A: 

Hi hkda150,

you can update a set of columns (you still have to list the columns once):

SQL> UPDATE table_a
  2     SET (ID, NAME, etc)
  3         = (SELECT * FROM table_b WHERE table_b.id = table_a.id)
  4   WHERE table_a.id IN (SELECT ID FROM table_b);

1 row updated
Vincent Malgrat
Exactly what I put, but much cleaner and nicer :o)
Ardman
Yes, I thought that there might be another way to do it. But it is ok for me that way. Thanks Ardman and Thanks Vincent.
hkda150
You can't use the SELECT * unless the table structure of table_b is exactly like the SET list; you'll probably have to list the fields in the SELECT
Leslie