tags:

views:

236

answers:

3

Suppose I have

  • table first_table which has an FK to table second_table
  • table second_table which has column called name_field

Now, I want to add a column in first_table called name_field and fill it with the one on the associated second_table.

How should I fill the values purely using SQL?

(this is Oracle, if that matters)

+1  A: 

You can make a trigger in the FK table to do so automaticaly:

UPDATE table1
SET <field> = (select <field> from inserted where id=table1.id)
j.a.estevan
-1 because triggers are the work of the devil. They make system maintenance and debugging more difficult.
David Aldridge
If you know that this field is only updated by a trigger, I can't find problems with that. Triggers are good for some task and not for anothers, is your selection of using it or not the work of the devil ;)
j.a.estevan
+1  A: 
update (select first_table.name_field nf1,
               second_table.name_field nf2
          from first_table,
               second_table
          where ... (join condition) ...
        )
set nf1 = nf2
David Aldridge
+1  A: 

Potentially there are 2 different tasks: 1) initialize values in the new column I think that syntax below is the most universal UPDATE table1 SET <field> = (select <field> from table2 where id=table1.id) 2) synchronize values between 2 column in 2 tables based on the approach of j.a.estevan