Changing the same column in two tables at the same time

Hi,
Oracle 10g2
I have 2 tables:
1. tab1 : Stores people info
2. tab2 : Stores people insurance info
Both have an address field.
What I need to do is when tab1.address is updated I want the tab2.address to update automatically and
when tab2.address is updated I want tab1.address to update.
Is there a way to do this using triggers without having these triggers mutate?
Thanks,
Oleg
Edited by: user635344 on Oct 8, 2009 11:04 AM

Hi, Oleg,
Centinul, Toon, Hoek and Peter are right. (It would be unusual if any one of them were wrong.)
The addresses really ought to be in one table.
If you really must have them in two (or more) tables, then don't INSERT or UPDATE addresses direectly into the tables; use a separate stored procedure, not a trigger.
If you really must use a trigger (and this means a trigger on each table), then before each trigger updates the other table, check a flag to see if the current table is being updated because of DML on the other, and, if so, do nothing. If the current table is not being updated because of DML on the other, then set the flag before doing the update.
In the example below, I used a package variable as the flag. You could also use a SYS_CONTEXT or a Global Temporary Table.
CREATE TABLE tab1
(      id    NUMBER
,      addr  VARCHAR2 (25)
DROP TABLE     tab2;
CREATE TABLE tab2
(      id    NUMBER
,      addr  VARCHAR2 (25)
CREATE OR REPLACE PACKAGE pk_x
AS
    -- This package contains no functions or procedures, only 1 variable:
    table_of_origin     varchar2 (30);
END     pk_x;
CREATE OR REPLACE TRIGGER     tab1_aiu
AFTER INSERT OR UPDATE OF addr on tab1
FOR EACH ROW
BEGIN
     IF  pk_x.table_of_origin  IS NULL
     THEN
          pk_x.table_of_origin := 'TAB1';
          UPDATE  tab2
          SET     addr     = :NEW.addr
          WHERE     id     = :NEW.id;
          pk_x.table_of_origin := NULL;
     END IF;
END     tab1_aiu;
CREATE OR REPLACE TRIGGER     tab2_aiu
AFTER INSERT OR UPDATE OF addr on tab2
FOR EACH ROW
BEGIN
     IF  pk_x.table_of_origin  IS NULL
     THEN
          pk_x.table_of_origin := 'TAB2';
          UPDATE  tab1
          SET     addr     = :NEW.addr
          WHERE     id     = :NEW.id;
          pk_x.table_of_origin := NULL;
     END IF;
END     tab1_aiu;
/I made this example as simple as possible. Production code would be a lot more complicated (e.g., checking to see if id was changed).
I tested this using the DML statements below.
The contents of both tables is shown after each statement.
INSERT INTO tab1 (id, addr) VALUES (1, '1 First St.');
      ID_1 ADDR_1                          ID_2 ADDR_2
         1 1 First St.
INSERT INTO tab2 (id, addr) VALUES (1, 'Forstagatan 1');
      ID_1 ADDR_1                          ID_2 ADDR_2
         1 Forstagatan 1                      1 Forstagatan 1
UPDATE        tab1
SET        addr     = 'Primo Place'
WHERE        id     = 1;
      ID_1 ADDR_1                          ID_2 ADDR_2
         1 Primo Place                        1 Primo PlaceThe query that displayed the contents is:
SELECT  tab1.id           AS id_1
,     tab1.addr     AS addr_1
,     tab2.id           AS id_2
,     tab2.addr     AS addr_2
FROM                tab1
FULL OUTER JOIN           tab2     ON     tab1.id     = tab2.id
ORDER BY   NVL (tab1.id, tab2.id);

Similar Messages

  • Merge Two Tables with the same columns but different data

    I have a table that has the following columns:
    Current Table Definition
    commonname
    family
    genus
    species
    subspecies
    code
    I have a number of entries that don’t fit the current table definition – that is that they only have a common name or description and a code. These records don’t actually represent a species but are needed for data entry because they represent an object that may be encountered in the study (Bare Ground – which isn’t a species but would need to be recorded if encountered). So I would really like 2 tables:
    Table 1 Miscellaneous
    name
    code
    Table 2 Plant Species
    commonname
    family
    genus
    species
    subspecies
    code
    I would like two tables so I can enforce certain constraints on my species table like requiring that the family, genus, species, subspecies combination is unique. I can’t do this if I have all the “other” records that don’t have a family, genus, species, or subspecies unless I put in a lot of dummy data into the fields to make each record unique. I don’t really want to do this because these miscellaneous records really don’t represent a specific species.
    So – the problem is that while I want this data separate I will need to point a column from another table to the code column in both tables.
    How is this best done? Table? View? Merge?

    Hi,
    Actually you don't have to use scope refs. Sorry but I misunderstood you earlier. Here is a complete example that does exactly what you want. Notice how I added the constraint to the materialized view. Also notice when we try to insert a code in tbl3 that doesn't exist in the view, we get an error. HTH.
    SQL> create table tbl1 (name varchar2(10), code varchar2(3) primary key);
    Table created.
    SQL> create table tbl2 (commonname varchar2(10), code varchar2(3) primary key);
    Table created.
    SQL> insert into tbl1 values ('n1','c1');
    1 row created.
    SQL> insert into tbl1 values ('n2','c2');
    1 row created.
    SQL> insert into tbl1 values ('n3','c3');
    1 row created.
    SQL> insert into tbl2 values ('name1','c1');
    1 row created.
    SQL> insert into tbl2 values ('name2','c2');
    1 row created.
    SQL> insert into tbl2 values ('name3','c3');
    1 row created.
    SQL> commit;
    Commit complete.
    SQL> create materialized view view1 as select name, commonname, tbl1.code from tbl1, tbl2 where tbl1.code = tbl2.code;
    Materialized view created.
    SQL> select * from view1;
    NAME COMMONNAME COD
    n1 name1 c1
    n2 name2 c2
    n3 name3 c3
    SQL> create table tbl3 (code varchar2(3), record varchar2(1));
    Table created.
    SQL> alter table view1 add constraint view1pk primary key (code); -- <-Note how I added a constraint to the view
    Table altered.
    SQL> alter table tbl3 add constraint tbl3fk foreign key (code) references view1(code);
    Table altered.
    SQL> insert into tbl3 values ('c1','r');
    1 row created.
    SQL> insert into tbl3 values ('c99','r');
    insert into tbl3 values ('c99','r')
    ERROR at line 1:
    ORA-02291: integrity constraint (RAJS.TBL3FK) violated - parent key not found
    SQL> spool of;
    -Raj Suchak
    [email protected]

  • How to write a case statement for the totals column of two different years (2013 and 2014) of the same month so that I can get a +/- column

    Please Help!!!
    How to write a case statement for the totals column of two different years (2013 and 2014) of the same month so that I can get a +/- column.
                                      January 2014         January
    2013                            +/-
                    Region   Entry   Exit  Total    Entry   Exit   Total   (Total of Jan2014-Total of Jan2013)
                    A               2         3      
    40        5       7        30                    40-30= 10

    What is a table structure? Sorry cannot test it right now..
    SELECT <columns>,(SELECT Total FROM tbl WHERE Y=2014)-(SELECT Total FROM tbl WHERE Y=2013)
    FROM tbl
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • How can I make my query to compare only columns of two tables... not the storage information?

    11GR2
    =-----------------------------------
    I am using below querry to compare two table that has same name, under two different users... But after making storage information false like below and  if the storage information is different on column level than it create "Alter modify " statements for the column ... How can I make my query to compare only columns of two tables... not the storage information?
    begin
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'PRETTY', TRUE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'SQLTERMINATOR',TRUE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'SEGMENT_ATTRIBUTES', FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'STORAGE', FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'TABLESPACE',FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'CONSTRAINTS',FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'REF_CONSTRAINTS',FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'CONSTRAINTS_AS_ALTER',FALSE);
    End;
    select REGEXP_REPLACE(dbms_metadata_diff.compare_alter('TABLE','TABLE_NAME_A','TABLE_NAME_A','USER1','USER2'),('USER1...'),'', 1, 0, 'i') from dual

    I am using below querry to compare two table that has same name, under two different users... But after making storage information false like below and  if the storage information is different on column level than it create "Alter modify " statements for the column ... How can I make my query to compare only columns of two tables... not the storage information?
    If you want help you have to SHOW us what you are doing and how you are doing it; you can't just try to tell us in your own words.
    We can't see your computer screen.

  • Selecting columns from two table is slow but same

    I am selecting 27 columns from two tables
    which running for more than 30 minutes. but
    if I select count(*) with the same query
    except the columns it is coming in seconds.
    Where is the error?

    If you post
    1) The table definitions for the underlying tables
    2) The indexes that are on the tables
    3) The two SQL statements you're running
    4) The explain plan for both statements
    we can probably be of some assistance.
    My guess is that the count(*) is able to return much more quickly because the optimizer is able to use a significantly faster query plan that is based on an index which the longer-running query cannot utilize. Without the information I've requested, though, it's hard to do more than speculate.
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • Data from two tables in the same row in XML transformation

    Hi,
        I am using XML transformation for generating excel file which is to besent as email attachment.
        Here  I want to display the data from two internal tables in the same row in the excel. .I am using   <tt:loop ref=".<table name>"> ...  </tt:loop> for looping through the table. Can I loop two table simultaneously ? In that case how will I specify the fields in each table . Some of the fields in two tables are of same name and type.
    Please help...
    Thanks,
    Jissa

    Hello Brian,
    Thank you for your answer. It is approach I will use, I think. However let me ask: Would it be possible to have a Version in this layout, too? I mean to see, which value comes from Version A and which comes from Version B? Something like this:
    Calendar Month Version Sales Amount
    2011.01  B  200
    2011.02  B  300
    2011.03  A  260
    2011.04  A  230
    2011.05  A  200
    A

  • How to use the TableSorter for two tables at the same view?

    Hello,
    I am using the TableSorter object in order to sort Dynpro tables.
    Suppose I have two tables at the same view, is it possible to use it seperatly for both of them?
    I assume that at the wdModifyView method I will need to catch the table that the user clicked on, yet I don't have an idea of how to do it...

    Hi Roy,
    Constructor of TableSorter
    public TableSorter(IWDTable table, IWDAction sortAction, Comparator[] comparators)
    So, you have to create instance of TableSorter class for each table on the view.
    best regards, Maksim Rashchynski.

  • Updating two tables at the same time

    Please,
    Does someone have an idea on how to update two tables at the same times?
    Thanks a lot in advance

    I was thinking about a single session and single update command.
    That's why I thougth someone else could have a clue.
    Thank you

  • How do I join two tables in the same database and load the result into a destination table in a SSIS package

    Hi,
    I have a query that joins two tables in the same database, the result needs to be loaded in a destination DB table.  How do I do this in SSIS package?
    thank you !
    Thank You Warmest Fanny Pied

    Please take a look at these links related to your query.
    http://stackoverflow.com/questions/5145637/querying-data-by-joining-two-tables-in-two-database-on-different-servers
    http://stackoverflow.com/questions/7037228/joining-two-tables-together-in-one-database

  • Two tables in the same uix page

    Hi! I work with Jdeveloper and UIX with the framework Jheadstart. I need to save data of two tables at same time; i mean , two tables in the same page which save with the same submitbutton. i have made some tries editing the service file, some templates and of course the page, but sometimes it works and sometimes not, i dont know what's happening and i really need to resolve this problem urgently. i hope someone can help me and i'd thank you a lot.
    Thanks for your atention.

    I'm sorry, but I'm going to need more details before I can help. If you can provide stripped down versions of your UIX page and Java code, perhaps I can be of service. Also, I would like to know which JDeveloper and UIX versions you are using.
    Ryan Pollock
    UIX Team

  • Two tables on the same page. Is it possible?

    Hi all,
    I followed the multi-slect sample in Winston's blog and everything is working. However, when I tried to put two tables on the same page, the selections are all messed up. When I looked at the code again I realized the line
    RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
    in the setSelected(Object object) method.
    In the case that there are more than one tables on one page, how does the code which table it is refering to? Or how the code should be different so we can have multi tables with selectable rows on the same page? Thnx.

    Thanks. But how do you tie the TableSelectPhaseListeners to their respected tables.
    This is Winston's code for row select (1 table)
    private TableSelectPhaseListener tablePhaseListener = new TableSelectPhaseListener();
    public void setSelected(Object object) {
    RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
    if (rowKey != null) {
    tablePhaseListener.setSelected(rowKey, object);
    public Object getSelected(){
    RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
    return tablePhaseListener.getSelected(rowKey);
    public Object getSelectedValue() {
    RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
    return (rowKey != null) ? rowKey.getRowId() : null;
    public boolean getSelectedState() {
    RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
    return tablePhaseListener.isSelected(rowKey);
    For two tables. Do I just repeat the code like this?
    private TableSelectPhaseListener tablePhaseListener1 = new TableSelectPhaseListener();
    public void setSelected1(Object object) {
    RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
    if (rowKey != null) {
    tablePhaseListener1.setSelected(rowKey, object);
    public Object getSelected1(){
    RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
    return tablePhaseListener1.getSelected(rowKey);
    public Object getSelectedValue1() {
    RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
    return (rowKey != null) ? rowKey.getRowId() : null;
    public boolean getSelectedState1() {
    RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
    return tablePhaseListener1.isSelected(rowKey);
    private TableSelectPhaseListener tablePhaseListener2 = new TableSelectPhaseListener();
    public void setSelected2(Object object) {
    RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
    if (rowKey != null) {
    tablePhaseListener2.setSelected(rowKey, object);
    public Object getSelected()2{
    RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
    return tablePhaseListener2.getSelected(rowKey);
    public Object getSelectedValue2() {
    RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
    return (rowKey != null) ? rowKey.getRowId() : null;
    public boolean getSelectedState2() {
    RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");
    return tablePhaseListener2.isSelected(rowKey);
    Edited by: Thomas5 on Jan 18, 2008 5:28 AM

  • Compare two columns between two tables

    Hi all,
    I have two separate datasets in Table 1 and Table 2.
    Both datasets have Column A First name and Column B Last name in common.
    The data in the subsequent columns is different.
    Some of the people listed in each table are the same.
    I want to delete the people from Table 1 who are in table 2.
    If I run a formula like this =COUNTIF(Table 1 :: A2:A200, A2) I can return a 1 or 0, use conditional formatting to colour that cell, sort the table and delete all the rows containing 1.
    However that only checks for First Name.
    What I need to do is check if First name AND Last name in Table 1 are the same as First Name AND Last Name in Table 2 - and then return a True of False (1 or 0 or anything) in a separate column.
    Please help.
    Thanks in advance.
    M.

    Moich wrote:
    Presumably this lets me compare multiple values across multiple tables also?
    Moich,
    As you will see as you become familiar with this function, it can only count rows in one table. The comparison (criteria) values can come from anywhere, but what you are counting are "records" that meet the multiple criteria. A record is one row. I think that was your question, but I'm not positive.
    I can't seem to find how to insert formulas into the conditional rules.
    You'll have to put the formulas elsewhere and refer to them with simple comparisons.
    Jerry

  • How to update two columns in two tables?

    hi friends
    I have two tables linked to each other through SaleNo and SaleDT. their structure as below
    Sales Table============
    SaleNo int PK auto increment
    SaleDT Datetime PK
    Qnty decimal
    Units decimal
    Invoices table
    =================InvoiceNo int PK Auto incremented
    InvoiceDT Datetime
    SaleNo int FK
    SaleDT Datetime FK
    Note that SaleDT column is NOT assigned with getDate() expression.
    1. what I need to do is update the SaleDT column of Sales table and Invoices table with the value '2013-01-31 10:31:55.813', how do I do this without manually breaking the link between the tables?
    2. Assume SaleNos 15 to 27 needs update the SaleDT to '2013-06-12 10:31:55.813', how do I do this complex operation where I I have update SaleDt column of two table of SaleNo range from 15 to 27?
    thanks
    I use Visual studio 2012 Ultimate and SQL server 2008 developer edition!

    Why not below? May be you will not be able to change your design now, but just want to share.
    Sales Table============
    SALEID int PK autoincrement
    SaleNo int
    SaleDT Datetime
    Qnty decimal
    Units decimalUNIQUE (Saleno,SaleDT)
    Invoices table
    =================InvoiceNo int PK Auto incremented
    InvoiceDT Datetime
    SALEID int FK

  • Is it possible to change nunmber of columns dynamically in table control

    Is it possible to change number of columns dynamically in table control? if so how it could be done?
    Thnaks in advance.
    Sounder

    You can update the table control in your program, the table control is a structure of the type CXTAB_CONTROL of TYPE-POOLS cxtab.
    There you can hide or display column the same way you do for fields in LOOP AT SCREEN. there you will ahve to LOOP AT <control>-COLS.
    TYPE-POOL CXTAB .                                                                               
    TYPES:                                                                               
    BEGIN OF CXTAB_COLUMN,                                                          
             SCREEN      LIKE SCREEN,     "Attributes struktur SCREEN                      
             INDEX       TYPE I,         "Position of a column on the screen               
             SELECTED(1) TYPE C,          "Indicator 'column selected'                     
             VISLENGTH   LIKE ICON-OLENG, "Visualised length of a column                   
             INVISIBLE(1) TYPE C,         "Indicator 'column invisible'                    
           END   OF CXTAB_COLUMN,                                                                               
    BEGIN OF CXTAB_CONTROL,                                                         
             FIXED_COLS    TYPE I, "Number of fixed columns                                
             LINES         TYPE I, "Number of lines to display                             
             TOP_LINE      TYPE I, "Top line during next PBO                               
             CURRENT_LINE  TYPE I, "Current line during LOOP/ENDLOOP                       
             LEFT_COL       TYPE I, "Fist scrollable column after fixed area               
             LINE_SEL_MODE    TYPE I, "Line-selection  : none(0), single(1),               
             COL_SEL_MODE     TYPE I, "Column-selection:        multiple(2)                
             LINE_SELECTOR(1) TYPE C, "Indicator: 'With line-selection col'                
             V_SCROLL(1) TYPE C,            "not used                                      
             H_GRID(1) TYPE C,        "Indicator: 'Horizontal  grid-lines'                 
             V_GRID(1) TYPE C,     "Indicator: 'Vertikal    grid-lines'                    
             COLS      TYPE STANDARD TABLE OF CXTAB_COLUMN                                 
                            WITH NON-UNIQUE DEFAULT KEY,                                   
             INVISIBLE(1) TYPE C,                                                          
           END   OF CXTAB_CONTROL,                                                         
    Regards

  • How to find the structural difference between two tables

    Hi all,
    How to find the structural difference between two tables .
    Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - Production
    PL/SQL Release 11.1.0.7.0 - Production
    CORE 11.1.0.7.0 Production
    TNS for 32-bit Windows: Version 11.1.0.7.0 - Production
    NLSRTL Version 11.1.0.7.0 - Production
    Thanks,
    P Prakash

    you could try something similar to this, for each table pair that you want to compare:
    SELECT 'TABLE_A has these columns that are not in TABLE_B', DIFF.*
      FROM (
            SELECT  COLUMN_NAME, DATA_TYPE, DATA_LENGTH
              FROM all_tab_columns
             WHERE table_name = 'TABLE_A'
             MINUS
            SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH
              FROM all_tab_columns
             WHERE table_name = 'TABLE_B'
          ) DIFF
    UNION
    SELECT 'TABLE_B has these columns that are not in TABLE_A', DIFF.*
      FROM (
            SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH
              FROM all_tab_columns
             WHERE table_name = 'TABLE_B'
             MINUS
            SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH
              FROM all_tab_columns
             WHERE table_name = 'TABLE_A'
          ) DIFF;that's assuming, column_name, data_type and data_length are all you want to compare on.

Maybe you are looking for

  • How can I diagnose or resolve missing AD groups for target audience rules

    Hello everyone, I'm having some problems with the target audiences I have set up in my SharePoint 2010 farm. I have set up a single rule for each target audience in Central Administration, pointing to a group in Active Directory. Up until a couple of

  • Photoshopcc installed fine on windows 8 but when opened windows immediately says problem and shuts program.

    I have just installed photoshop and lightroom cc on my windows 8. Lightroom is fine. Photoshop seems fine but a few seconds after opening a windows box says there's a problem and shuts the program. Have tried re-starting computer, signing out and bac

  • Implementing portal for SAP Reports

    Dear All, we have SAP 4.7 E1.1 system. we are thinking to implement the portal with an objective of only allowing the users to access the production reports online. we have both Stardard reports & Z reports. we are under the impression that we can st

  • Source System creation error

    Hi.. I cannot create R/3(productive) source system at BW (development) I checked password, cross-client and client specific are all changeble (t-code SCC4) and namespaces, sofeware are also modifiagle (t-code SE06) at R/3. At BW, RFC connection is Ok

  • Used DC's

    Hi In developign an Webdynpro application I want to add a Local DC Component CompB to the Root Component CompA. To do this I nagivate to DC MetaData -> DC Definition -> Used DC's -> Add Used DC's (from Context Menu). From here I can navigate the othe