Select all column names from Table1;
Select all column names from Table2;
For each column in Table1 {
if column exists in Table2 then
Table1.column.value = Table2.column.value;
}
What is the best way to implement this? Requires Free Membership to View
The best way to do this is to use PL/SQL and the EXECUTE IMMEDIATE command. Something similar to the following:
DECLARE
CURSOR c1 IS select column_name
from user_tab_columns
where table_name='table1'
INTERSECT
select colum_name
from user_tab_columns
where table_name='table2';
col_name USER_TAB_COLUMNS.COLUMN_NAME%TYPE;
update_string VARCHAR2(255);
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO col_name;
EXIT WHEN c1%NOTFOUND;
update_string:='UPDATE table1 SET '||col_name||
'=table2.'||col_name;
EXECUTE IMMEDIATE update_string;
END LOOP;
END;
/
This PL/SQL block has a cursor which finds all columns
of the same name in both tables. Then, for each of
those columns, an UPDATE command is dynamically built
and then executed. My UPDATE command did not take into
account that you may want a WHERE clause to limit
which rows in the table get updated. You'll have to
supply that if applicable.
For More Information
- Dozens more answers to tough Oracle questions from Brian Peasland are available.
- The Best Oracle Web Links: tips, tutorials, scripts, and more.
- Have an Oracle or SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical Oracle and SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
This was first published in November 2002

Join the conversationComment
Share
Comments
Results
Contribute to the conversation