Constraint & update

Hi friends,
We have to update a single column data in about 10 tables which has child/parent table relations, pk/fk constraints.. The column that we are updating is a part of primary key in half of the tables and part of foreign key in the other half tables.. I'm thinking of disabling all the foreign key constraints in the tables then update the column data then enable the foreign key constraints in these tables. I'm not sure if there will be any other rising issues when we do this... Of course we will be trying it out on the test database but is there any other efficient way to do this?
Thanks so much

newbiegal wrote:
Hi friends,
We have to update a single column data in about 10 tables which has child/parent table relations, pk/fk constraints.. The column that we are updating is a part of primary key in half of the tables and part of foreign key in the other half tables.. I'm thinking of disabling all the foreign key constraints in the tables then update the column data then enable the foreign key constraints in these tables. I'm not sure if there will be any other rising issues when we do this... Of course we will be trying it out on the test database but is there any other efficient way to do this?
Thanks so muchIf you're absolutley sure that the updated has matched perfectly in both parent and child (i.e. ABC has become
DEF in both), then you can save time if you have huge tables, when re-enabling the foreign key constraints,
by not validating the foreign key (ENABLE NOVALIDATE).
However, in future, I advise that whoever designs your tables doesn't choose a primary key that has meaning:
i.e. use a surrogate sequence generated key; then you will not need to modify them. If a PK has meaning
it is likely that the business will want to change it for some reason.

Similar Messages

  • Appling Constraints To Avoid  Cyclic In Oracle

    Hi Guys,
    I have a table category_defn ,In this table there are 3 columns category_id,parent_category_id,bank_id.
    I have a requirement like if 1 has two children 2 and 3 , I need to have a constraint which will restrict the data entry
    1 as a child of 3.That means it should not allow the cyclic order in the parent and child
    I am wondering is there any constraint or way to achieve this in Oracle with out the help of triggers.
    Any ideas,suggestions will be highly appreciated.
    Thanks,
    Papi

    957590 wrote:
    Is there any way even if in the complex manner to achieve this.Here's a try. It seems to "work", but it makes the hierarchy much harder to change.
    The idea is:
    - Use purely technical IDs for primary key and parent
    - Never allow a parent id to be greater than a child id (check constraint)
    - Have your "real" category_id be UNIQUE.
    - Make the constraint on the "real" id DEFERRABLE so you can update it.drop sequence s;
    create sequence s;
    drop table t;
    create table t (
      tech_id number primary key,
      parent_tech_id number,
      category_id number unique deferrable,
      check(parent_tech_id < tech_id)
    alter table t add constraint fk_t
    foreign key (parent_tech_id) references t(tech_id);
    insert into t values(s.nextval,null, 1);
    insert into t values(s.nextval,(select max(tech_id) from t), 2);
    insert into t values(s.nextval,(select max(tech_id) from t), 3);
    select * from t;
       TECH_ID PARENT_TECH_ID CATEGORY_ID
             1                          1
             2              1           2
             3              2           3 Test of the check constraint:update t set parent_tech_id = 3 where tech_id = 1;
    SQL Error: ORA-02290: check constraint (STEW.SYS_C0034169) violatedUpdate the "real" IDset constraints all deferred;
    update t set category_id =
    case category_id when 1 then 3 when 3 then 1 end
    where category_id in(1,3);
    set constraints all immediate;
    commit;The drawback to this idea is that some changes to the hierarchy are harder to do. What if you have lots of descendants and you just want to put the ancestor under a newer row? You either have to manually adjust the TECH_ID of the newer row, or do lots of UPDATEs, or do lots of DELETEs + INSERTs. Does this solution reduce complexity or just move it somewhere else?
    At least with this solution you don't need triggers!
    P.S. I did this "quick and dirty". In real life, always put names on deferrable constraints so you can defer them by name.
    Edited by: Stew Ashton on Jan 28, 2013 1:44 PM

  • SQL Triggering Unique constraint

    Hi,
    I'm not quite sure why this SQL is not working. In a table called t_car I want to change the data in the SECTIONAA_NO column so they end with a J if there is not already one in the table. There is a unique constraint on the column.
    This SQL is triggering the unique constraint.
    update t_car t
    set t.SECTIONAA_NO = substr(t.SECTIONAA_NO, 1,5) || 'J'
    where not exists
    (select 1 from t_car j
    where j.SECTIONAA_NO = substr(t.SECTIONAA_NO, 1,5) || 'J')
    But when I put it in a PL/SQL loop (below) and do the updates row by row it works. What am I doing wrong in the SQL above?
    declare
    begin
    for rec in (select car_id from t_car) loop
    begin
    update t_car t
    set t.SECTIONAA_NO = substr(t.SECTIONAA_NO, 1,5) || 'J'
    where not exists
    (select 1 from t_car j
    where j.SECTIONAA_NO = substr(t.SECTIONAA_NO, 1,5) || 'J')
    and car_id = rec.car_id;
    exception
    when others then dbms_output.put_line(rec.car_id); rollback;
    end;
    end loop;
    end;

    All of the data in the column is of length 6. I want to change the last letter to be 'J' if the new value does not already exist. There's a unique constraint on the column.
    I don't think
    update t_car t
    set t.SECTIONAA_NO = substr(t.SECTIONAA_NO, 1,5) || 'J'
    where t.SECTIONAA_NO <> substr(t.SECTIONAA_NO, 1,5) || 'J')
    will work as I need to check the entire table for the existence of the new value,

  • Map ID

    How do i create Map ID's?
    RoboHelp Report
    Possible Project Errors for RAAS HelpFile
    Created by lbeaulieu on 1/7/2008 1:01:21 PM
    Project Location: F:\Projects\RAAS Documentation\RAAS
    HelpFile\RAAS HelpFile.hpj
    Diagnostic Report Summary
    There are 62 topics with no Map ID.
    Diagnostic Report Details
    The following topics do not have a Map ID assigned to them.
    Adding New Options
    Batching work order items
    Build and Verify
    Changing a Part Description/Part Number
    Company Settings
    Constraint Updating
    Correcting Errors to TMI Entries
    Creating a Part
    Creating a TMI Log Sheet Record
    Creating Job Cards
    Crediting Work Order Items
    Defining Triggers
    Deleting a Part
    Entering a Missed TMI Log Sheet Record
    Filing Part Request
    Filling Part Requests by Purchasing
    Filling Part Requests from Inventory
    Finding a Job Card
    Generating a Maintenance Forecast
    Getting Started with RAAS
    Internal Repair Job Cards -Part Requests
    Internal Repair Job Cards
    Introduction to Maintenance Planning
    Introduction to Part Management
    Introduction to Production
    Introduction to RAAS
    Introduction to Reports
    Introduction to Stores
    Introduction to Technical Maintenance Input
    Issuing Jobs from a Maintenance Forecast
    Maintenance Planning
    Method One
    Method Two
    Min Max
    More about Opening Job Cards
    New Purchase Items
    Opening Job Cards
    Options
    Part Editor
    Part Requests Find
    Part Transfers
    Part Tree
    Personal Preferences
    Printing Technical Logs
    Purchase List-Adding Items to an Open Purchase Order
    Purchasing on a New Purchase Order
    Purchasing Parts by Creating a New Purchase Order
    Purchasing Parts by Issuing to an Existing Purchase Order
    Quick Find
    RAAS Report Map
    Receiving Items on a Purchase Order
    Report
    Requesting Parts from a Job Card
    Requests for non-tracked and non-master parts
    Resequencing TMI Log Sheets
    Responding to Requests for New Purchase Items
    Reversing a work order issue
    Setting up a Part
    Trace Information
    Un-batching work order items
    Work Order Entries
    Work Order Listing

    Hi - not sure if you got an answer to this already in another
    forum, but the quickest way to find what you need on map IDs is to
    call up the RoboHelp for Word Help file and look up "Map IDs" in
    the Index. The topics there will give you the steps to follow.
    Don't worry - RH will make it seem pretty straightforward. Good
    luck!

  • My identity values has jumped how to set it normal

    Please can you someone help me in the steps in setting the identity value back
    I have the table which has a identity column and it was good untill 2 days back and now suddenly the value has bumped up by 500000000 and giving its own values to the identity thing which should have ben sequential.
    Please can some one give the steps to set it back
    is it
    1)bcp out the values
    2)run sp_changeattribute tablenmae,"identity_burn_max", 0, "[new_value]"(new values some value bigger than the preseent row count)
    3)then bcp in the values back
    plz let me know if thats the solution
    Its an urjently required
    version is 15.7 and non prod environment.
    Thanks

    A few additional items ...
    - foreign keys
    If the table's identity values make up part of a foreign key in another table then it'll be necessary to update those FK values at the same time.
    NOTE: Under this scenario it would not be a good idea to bcp the table's data out and back in as you'd lose track of which FK values to update in the other table.
    - foreign key RI constraints
    If the table's identity values make up part of a foreign key in another table, and said FK relationship is maintained by a FK RI constraint, it'll be necessary to drop the FK constraint, update the identity/FK-values, then put the FK RI constraint back in place.
    - triggers
    [For the update option] If the table has an update trigger you'll need to determine if the trigger logic should be applied during your updates. If you don't want the update trigger to fire you'll likely want to disable the update trigger, perform the updates, then re-enable the trigger.
    [For the bcp option] If the table has an insert trigger you'll need to determine if the trigger logic should be manually applied after bcp'ing the data back into the table (ie, insert trigger won't fire during a bcp in).
    - concurrent activity
    Obviously (?) you'll need to take into consideration when to perform the updates (or bcp's) so as to minimize issues with other users/processes trying to access the table, eg:
    a - bcp out, truncate table, bcp in : user/application aborts due to missing/changed data
    b - bcp out, truncate table, bcp in : user/application inserts new rows prior to bcp in thus (possibly) skewing the order of data in the table
    c - bcp or update : other user activity inserts a new row which generates a new identity value that is too large (ie, before you've had an opportunity to change the gap size, or before you've reset the max ident value), thus leading to a new row that needs to be bcp'd out/in or updated
    d - triggers/RI constraints : disabling triggers or dropping RI constraints means other users/applications could perform inserts/updates without benefit of the triggers/RI constraints

  • NULLABLE column is not updated after the NOT NULL constraint definition...

    Hi,
    SQL> select column_name,nullable from all_tab_columns where table_name='EMP';
    COLUMN_NAME                    NULLABLE
    EMPNO                          N
    ENAME                          Y
    JOB                            Y
    MGR                            Y
    HIREDATE                       Y
    SAL                            Y
    COMM                           Y
    DEPTNO                         Y
    CODE_POLEIS_DIAM               Y
    9 rows selected
    SQL> ALTER TABLE EMP add constraint emp_job_nn check(job is not null);
    Table altered
    SQL> select constraint_name from all_cons_columns
      2  where table_name='EMP';
    CONSTRAINT_NAME
    FK_DEPTNO
    PK_EMP
    EMP_JOB_NN
    SQL> select column_name,nullable from all_tab_columns where table_name='EMP';
    COLUMN_NAME                    NULLABLE
    EMPNO                          N
    ENAME                          Y
    JOB                            Y                         <---------'NULL'
    MGR                            Y
    HIREDATE                       Y
    SAL                            Y
    COMM                           Y
    DEPTNO                         Y
    CODE_POLEIS_DIAM               Y
    9 rows selected
    Why is not updated....????
    In Oracle ebook:
    Oracle® Database Reference
    10g Release 2 (10.2)
    Part Number B14237-02
    the comments about the NULLBLE column are as follows:
    "Specifies whether a column allows NULLs. Value is N if there is a NOT NULL constraint on the column or if the column is part of a PRIMARY KEY. The constraint should be in an ENABLE VALIDATE state."
    BUT BY DEFAULT ALL CONSTRAINTS ARE IN VALIDATE STATE
    (Ref: Oracle® Database SQL Reference
    10g Release 2 (10.2)
    Part Number B14200-02 )Note : I use OraDB 10g v.2
    Thanks a lot
    Sim

    Hi,
    Tom Kytes answer it before:
    SQL> create table t ( id int );
    Table created.
    SQL> desc t
    Name                            Null?    Type
    ID                                       NUMBER(38)
    SQL> alter table t add constraint t_nn check (id is not null);
    Table altered.
    SQL> insert into t (id) values (null);
    insert into t (id) values (null)
    ERROR at line 1:
    ORA-02290: check constraint (TANDREWS.T_NN) violated
    SQL> desc t
    Name                            Null?    Type
    ID                                       NUMBER(38)
    Followup July 16, 2003 - 10am US/Eastern:
    that is not a NOT NULL constraint, that is a check constraint
    ops$tkyte@ORA920LAP> create table t ( x int );
    Table created.
    ops$tkyte@ORA920LAP> alter table t modify x not null;
    Table altered.
    ops$tkyte@ORA920LAP> set linesize 50
    ops$tkyte@ORA920LAP> desc t
    Name                    Null?    Type
    X                       NOT NULL NUMBER(38)To see the full thread in asktom, please refer to:
    - http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1338402651192
    Cheers,
    Francisco Munoz Alvarez
    http://www.oraclenz.com

  • Unique constraint violation while updating a non PK column

    Hi,
    I seem to have found this strange error.
    What I try to do is bulk fetch a cursor in some table arrays. with limit of 1000
    Then using a forall and a save exceptions at the end
    I update a table with the values inside one of the table arrays.
    The column I update is not part of a PK
    I catch the error message: ORA-24381
    by using PRAGMA exception_init(dml_errors, -24381);
    and later on :
    WHEN dml_errors THEN
    errors := SQL%BULK_EXCEPTIONS.COUNT;
    FOR i IN 1..sql%BULK_EXCEPTIONS.count LOOP
    lr_logging.parameters:= 'index = ' || sql%BULK_EXCEPTIONS(i).error_index || 'error = ' ||Sqlerrm(-sql%BULK_EXCEPTIONS(i).error_code) ;
    END LOOP;
    I insert these errors in another table. and i get 956 errors
    first one is :
    index = 3error = ORA-00001: unique constraint (.) violated
    last one is
    index = 1000error = ORA-00001: unique constraint (.) violated
    How can this be.Since i don't update in a PKcolumn.
    FULL CODE IS:
    PROCEDURE Update_corr_values( as_checkdate_from IN VARCHAR2,
    as_checkdate_until IN VARCHAR2,
    as_market IN VARCHAR2
    IS
    LS_MODULE_NAME CONSTANT VARCHAR2(30) := 'update_values';
    lr_logging recon_logging.logrec;
    CURSOR lc_update IS
    SELECT /*+ORDERED*/c.rowid,c.ralve_record_id,d.value,c.timestamp,f.value
    FROM rcx_allocated_values a,
    rcx_allocated_values b,
    meter_histories e,
    rcx_allocated_lp_value c,
    rcx_allocated_lp_value d,
    counter_values f
    WHERE a.slp_type NOT IN ('S89', 'S88', 'S10', 'S30') --AELP
    AND b.slp_type IN ('S89', 'S88') --residu
    AND a.valid_from >= to_date(as_checkdate_from,'DDMMYYYY HH24:MI')
    AND a.valid_to <= to_date(as_checkdate_until,'DDMMYYYY HH24:MI')
    AND a.market = as_market
    AND a.market = b.market
    AND a.ean_sup = b.ean_sup
    AND a.ean_br = b.ean_br
    AND a.ean_gos = b.ean_gos
    AND a.ean_dgo = b.ean_dgo
    AND a.direction = b.direction
    AND a.valid_from = b.valid_from
    AND a.valid_to = b.valid_to
    AND c.ralve_record_id = a.record_id
    AND d.ralve_record_id = b.record_id
    AND c.TIMESTAMP = d.TIMESTAMP
    AND e.ASSET_ID = 'KCF.SLP.' || a.SLP_TYPE
    --AND f.timestamp between to_date(gs_checkdate_from,'ddmmyyyy') and to_Date(as_checkdate_until,'ddmmyyyy')
    AND e.SEQ = f.MHY_SEQ
    AND f.TIMESTAMP =c.timestamp - 1/24
    ORDER BY c.rowid;
    TYPE t_value IS TABLE OF RCX_ALLOCATED_LP_VALUE.VALUE%TYPE;
    TYPE t_kcf IS TABLE OF COUNTER_VALUES.VALUE%TYPE;
    TYPE t_timestamp IS TABLE OF RCX_ALLOCATED_LP_VALUE.TIMESTAMP%TYPE;
    TYPE t_ralverecord_id IS TABLE OF RCX_ALLOCATED_LP_VALUE.RALVE_RECORD_ID%TYPE;
    TYPE t_row IS TABLE OF UROWID;
    ln_row t_row :=t_row();
    lt_value t_value := t_Value();
    lt_kcf t_kcf := t_kcf();
    lt_timestamp t_timestamp := t_timestamp();
    lt_ralve t_ralverecord_id := t_ralverecord_id();
    v_bulk NUMBER := 1000;
    val number;
    kcf number;
    ralve number;
    times date;
    dml_errors EXCEPTION;
    errors NUMBER;
    PRAGMA exception_init(dml_errors, -24381);
    BEGIN
    --setting arguments for the logging record
    lr_logging.module := LS_MODULE_NAME;
    lr_logging.context := 'INFLOW_ALL_VALUES_PARTS';
    lr_logging.logged_by := USER;
    lr_logging.parameters := 'Date time started: ' || TO_CHAR(sysdate,'DD/MM/YYYY HH24:MI');
    -- log debugs
    recon_logging.set_logging_env (TRUE, TRUE);
    recon_logging.log_event(lr_logging,'D');
    OPEN lc_update;
    LOOP
    FETCH lc_update BULK COLLECT INTO ln_row,lt_ralve,lt_value,lt_timestamp,lt_kcf LIMIT v_bulk;
    FORALL i IN NVL(lt_value.first,1)..NVL(lt_value.last,0) SAVE EXCEPTIONS
    UPDATE RCX_ALLOCATED_LP_VALUE
    SET VALUE = VALUE * lt_value(i) * lt_kcf(i)
    WHERE rowid =ln_row(i);
    COMMIT;
    lt_value.delete;
    lt_timestamp.delete;
    lt_ralve.delete;
    lt_kcf.delete;
    ln_row.delete;
    EXIT WHEN lc_update%NOTFOUND;
    END LOOP;
    CLOSE lc_update;
    recon_logging.log_event(lr_logging,'D');
    lr_logging.parameters := 'Date time ended: ' || TO_CHAR(sysdate,'DD/MM/YYYY HH24:MI');
    recon_logging.log_event(lr_logging,'D');
    --to be sure
    COMMIT;
    EXCEPTION
    WHEN dml_errors THEN
    recon_logging.set_logging_env(TRUE,TRUE);
    lr_logging.module := 'updatevalues';
    lr_logging.context := 'exception';
    lr_logging.logged_by := USER;
    lr_logging.parameters := 'in dml_errors';
    recon_logging.log_event(lr_logging);
    errors := SQL%BULK_EXCEPTIONS.COUNT;
    lr_logging.parameters:=errors;
    recon_logging.log_event(lr_logging);
    lr_logging.parameters :=('Number of errors is ' || errors);
    --DBMS_OUTPUT.PUT_LINE('Number of errors is ' || errors);
    FOR i IN 1..sql%BULK_EXCEPTIONS.count LOOP
    lr_logging.parameters:= 'index = ' || sql%BULK_EXCEPTIONS(i).error_index || 'error = ' ||Sqlerrm(-sql%BULK_EXCEPTIONS(i).error_code) ;
    recon_logging.log_event(lr_logging);
    END LOOP;
    --recon_logging.set_logging_env(TRUE,TRUE);
    --recon_logging.log_event(lr_logging);
    commit;
    WHEN OTHERS THEN
    lr_logging.module := 'updatevalues';
    lr_logging.context := 'exception';
    lr_logging.logged_by := USER;
    recon_logging.set_logging_env(TRUE,TRUE);
    lr_logging.parameters := 'in others error=' || SQLERRM;
    recon_logging.log_event(lr_logging);
    commit;--to look which is truly the last (else only commit after 1000)
    --raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
    END Update_corr_values;

    Hi,
    No I didn't update a unique constraint.
    But I found out that there is a trigger that causes the unique constraint while updating in the table.
    Silly mistake.Didn't know there was a trigger there.
    Thx anyway.
    Greetz

  • Insert or Update a target with no constraints

    I am trying to figure out how to do an insert/update on a target table which doesn't have a constraint? In other words how to define a condition on this target table attribute to achieve this? please advice.
    ~Prabha

    ... you're right. But don't forget to set to No Constraints too. And proof your matching settings several times. Due to an error in 10gR2 the settings could change: Bug in OWB 10gR2: Several Loading Properties after sync
    Regards,
    Detlef

  • How to update ordered list having a constraint

    hi friends,
    I have to update a column for all the records in the table with a unique contraint
    ex-- select rec_no from tablename;
    9
    8
    7
    6
    5
    now i have to update this like
    select rec_no from tablename;
    8
    7
    6
    5
    4
    but when i am doing update tablename set rec_no=rec_no-1
    i am getting unique constraint error
    plz help me

    dj wrote:
    but when i am doing update tablename set rec_no=rec_no-1
    i am getting unique constraint error
    No you don't. Show us.
    Oracle ensures "statement level constraint" consistency. If you do this in one update statement (which is what you state above), then Oracle will not give you a constraint error.
    For if it did, then we all would have a serious problem: whether or not the update succeeds would then depend on the order in which Oracle (ie. the execution plan) happens to update the rows. And we can't have such 'undeterministic' behavior (similar to what we would have when Oracle did not provide us with the mutating table error...).
    So just try it, or show us:
    create table uk_test
    (i number not null unique)
    insert into uk_test values(4);
    insert into uk_test values(3);
    insert into uk_test values(2);
    commit;Now try both of these:
    update (select * from uk_Test order by i desc) set i=i-1;
    update (select * from uk_Test order by i) set i=i-1;They both succeed. Oracle allows temporary constraint violations during/inside the execution of one statement. There is no need to set this constraint to deferred here.
    I talk about statement level constraint consistency here too:
    http://rulegen.blogspot.nl/2012/01/statement-level-constraint-validation.html

  • Updating records for parent & child with integrity constraints

    Hello, I haven't used oracle in a few years and now running a lab and need to make a few changes for testing. no production data at all.
    What is the easiest way to change the parent and child tables? When I try to change the parent, oracle barks that the child is neglected, when i try to change the child first, then the parent is mad.
    If I need to set up a trigger, what is the simplest form?
    thanks much!

    Depends on what you want your data to look like. Since it's test, I would do what janeesh said. Disable the constraint on the tables, write a script to UPDATE all the necessary values in the parent and child table, and then re-enable the constraint.
    I like the idea of setting the constraint to ENABLE VALIDATE afterwards to check the data in the tables. This verifies that all the updates you did comply with the constraint. Essentially this just checks to see if you hosed anything in either table.

  • When the update statement will check the constraint violation ?

    Hello all,
    i am working on data masking of production data using oracle Translate function.i have created a function otis_mask using translate function to mask sensitive values .For this i am tesitng on a small table. i have created a table with single primary key column SSN.
    sql>desc SSN_MASK
    Name Null? Type
    SSN NOT NULL NUMBER(10)
    1) i have inserted the value 9949577766. if resulted mask value exist in table it should throw the constraint violation error.But it is not throwing any error.rows are properly updating .
    Eg:-
    Table contains below values.
    PA_DATA_SUB @qdsrih30 >select *from SSN_MASK;
    SSN
    7727399911
    9949577766
    9989477700
    UPDATE SSN_MASK SET SSN=otis_mask(SSN);
    if above update statement process 7727399911 first then resulted mask value is 9989477700.This value is already in the table.
    if the update statement process 9949577766 first then resulted mask value is 7727399911.This value is already in the table.
    in any of the above scenario update statement should have to throw constraint violation error. But its not happening. rows are properly updating . when the update statement checking the constraint violation ? after processing all the rows or processing of each row ?
    Please help me in understandding the update statement processing ?
    Thanks,
    Venkat Vadlamudi.

    1)created a function as below.
    CREATE OR REPLACE Function otis_mask(incol varchar2) return varchar2 is
    random_str varchar2(20);
    begin
    select (translate(incol,'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890','qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0842319576')) INTO random_str FROM DUAL;
    return random_str;
    end;
    2. create a table ssn_mask.
    create table ssn_mask(ssn number(10) primary key);
    3) inserted 3 rows as below.
    insert into ssn_mask values(9949577766);
    insert into ssn_mask values(7727399911);
    insert into ssn_mask values(9989477700);
    4)UPDATE SSN_MASK SET SSN=otis_mask(SSN);
    5) Table contains below rows.
    Sql >select *from SSN_MASK;
    SSN
    9949577766
    7727399911
    9989477700.
    6)UPDATE SSN_MASK SET SSN=otis_mask(SSN);
    If the above statement process first row 9949577766,then otis_mask function will return 7727399911 and update statement will update the value of 9949577766 to 7727399911 .At this case 7727399911 is already in the table.So update statement should have to throw primary key constraint violation error.
    If the above statement process second row 7727399911 first ,then otis_mask function will return 9989477700.and update statement will update the value of 7727399911 to 9989477700.At this case 9989477700 is already in the table.So update statement should have to throw primary key constraint violation error.
    But its not throwing any integrity constraint violation error.
    i just want to know when update statement will check the constraint ?
    is update statement will first process all records and kepp in handy the new values then update the table with new values (or) process the first row and update the new value with old value then process second row and update with new value so on ?
    Thanks,
    Venkat Vadlamudi.

  • Exception from HRESULT: 0x80131904 and Violation of PRIMARY KEY constraint 'AllUserDataJunctions_PK' on item.update

    HI,
    We have done following changes to Production environment.
    1. Migrated Application from 2007 to 2010
    2. Done User Domain Migration user MoveSP-User commmand
    3. Then we Run following command to block users from another domain.
    Set-SPSite -Identity 'SiteName' -UserAccountDirectoryPath "DC=xxx,DC=xxx,DC=xxx"
    After All above changes, application were working fine without a single bug. all Operation are working fine. Then suddenly from 2 days below error coming in ULS log.
    This error is thrown on item.update();
    Unknown SPRequest error occurred. More information: 0x80131904
    System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'AllUserDataJunctions_PK'. Cannot insert duplicate key in object 'dbo.AllUserDataJunctions'.  The statement has been terminated.     at System.Data.SqlClient.SqlConnection.OnError(SqlException
    exception, Boolean breakConnection)     at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)     at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler,
    SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)     at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()     at System.Data.SqlClient.SqlDataReader.get_MetaData()    
    at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBeh...
    avior, String resetOptionsString)     at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)     at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
    cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)     at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
    method)     at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)     at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)     at Microsoft.SharePoint.Utilities.SqlSession.ExecuteReader(SqlCommand
    command, CommandBehavior behavior, SqlQueryData ...
    ...monitoringData, Boolean retryForDeadLock)
    at Microsoft.SharePoint.SPSqlClient.ExecuteQueryInternal(Boolean retryfordeadlock)     at Microsoft.SharePoint.SPSqlClient.ExecuteQuery(Boolean retryfordeadlock)     at Microsoft.SharePoint.Library.SPRequestInternalClass.AddOrUpdateItem(String
    bstrUrl, String bstrListName, Boolean bAdd, Boolean bSystemUpdate, Boolean bPreserveItemVersion, Boolean bUpdateNoVersion, Int32& plID, String& pbstrGuid, Guid pbstrNewDocId, Boolean bHasNewDocId, String bstrVersion, Object& pvarAttachmentNames,
    Object& pvarAttachmentContents, Object& pvarProperties, Boolean bCheckOut, Boolean bCheckin, Boolean bMigration, Boolean bPublish, String bstrFileName, ISP2DSafeArrayWriter pListDataValidationCallback, ISP2DSafeArrayWriter pRestrictInsertCallback,
    ISP2DSafeArrayWriter pUniqueFieldCallback)     at Microsoft...
    ....SharePoint.Library.SPRequest.AddOrUpdateItem(String bstrUrl, String bstrListName, Boolean bAdd, Boolean bSystemUpdate, Boolean bPreserveItemVersion, Boolean bUpdateNoVersion, Int32& plID, String& pbstrGuid, Guid pbstrNewDocId, Boolean bHasNewDocId,
    String bstrVersion, Object& pvarAttachmentNames, Object& pvarAttachmentContents, Object& pvarProperties, Boolean bCheckOut, Boolean bCheckin, Boolean bMigration, Boolean bPublish, String bstrFileName, ISP2DSafeArrayWriter pListDataValidationCallback,
    ISP2DSafeArrayWriter pRestrictInsertCallback, ISP2DSafeArrayWriter pUniqueFieldCallback)     at Microsoft.SharePoint.SPListItem.AddOrUpdateItem(Boolean bAdd, Boolean bSystem, Boolean bPreserveItemVersion, Boolean bNoVersion, Boolean bMigration,
    Boolean bPublish, Boolean bCheckOut, Boolean bCheckin,...
    SqlError: 'Violation of PRIMARY KEY constraint 'AllUserDataJunctions_PK'. Cannot insert duplicate key in object 'dbo.AllUserDataJunctions'.'    Source: '.Net SqlClient Data Provider' Number: 2627 State: 1 Class: 14 Procedure: 'proc_CreateItemJunctionsVersion'
    LineNumber: 9 Server: 'xxxxxxxxx\xxxxx' a035fb89-0a86-4817-b531-f20a537a002a
    SqlError: 'The statement has been terminated.'    Source: '.Net SqlClient Data Provider' Number: 3621 State: 0 Class: 0 Procedure: 'proc_CreateItemJunctionsVersion' LineNumber: 9 Server: 'xxxxxxxx\xxxxxxx' a035fb89-0a86-4817-b531-f20a537a002a
    Please help!!!
    I am unable to find any solution.
    Regards,
    Yogesh Ghare
    EDIT - Just adding some extra points that come from observation .
    1. This Error comes when following scenario is true
    First Attempt: User udated item in List "Issue Tracking" from Datasheet view
    Second Attempt: User udate the same item in list from "Sharepoint UI or Custom aspx form".. After clickin on Save button this erro comes up.
    Third Attempt: If after error user updates the same itme from UI the the data get saved
    OR
    Third Attempt : If after error user updates the same itme from datasheet view User get Unresolve data confilct again and again.
    Above Scenario is true only for Existing items in lists. For Newly added Items this is not producible(erroe not generated).One of the ovbservation is that All the items which are having issue are migrated from 2007 to 2010

    Hello,
    I have the exact same issue. SharePoint List which is causing this issue has got around 140 fields (All kinds of field types).
    Do this happen only if there is a migration from one version to other?
    This List is created using custom code - List Instance and not using Out of box SharePoint.
    Please let me know if recreating the list (using OOB) or any other fix will resolve this issue.
    Below is the ULS log:
    Unknown SPRequest error occurred. More information: 0x80131904
    System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80131904  
     at Microsoft.SharePoint.Library.SPRequestInternalClass.AddOrUpdateItem(String bstrUrl, String bstrListName, Boolean bAdd, Boolean bSystemUpdate, Boolean bPreserveItemVersion,
    Boolean bPreserveItemUIVersion, Boolean bUpdateNoVersion, Int32& plID, String& pbstrGuid, Guid pbstrNewDocId, Boolean bHasNewDocId, String bstrVersion, Object& pvarAttachmentNames, Object& pvarAttachmentContents, Object& pvarProperties,
    Boolean bCheckOut, Boolean bCheckin, Boolean bMigration, Boolean bPublish, String bstrFileName, ISP2DSafeArrayWriter pListDataValidationCallback, ISP2DSafeArrayWriter pRestrictInsertCallback, ISP2DSafeArrayWriter pUniqueFieldCallback)   
     at Microsoft.SharePoint.Library.SPRequest.AddOrUpdateItem(String bstrUrl, String bstrListName, Boolean bAdd, Boolean bSystemUpdate, Boolean bPreserveItemVersion, Boolean bPreserveItemUIVersion,
    Boolean bUpdateNoVersion, Int32& plID, String& pbstrGuid, Guid pbstrNewDocId, Boolean bHasNewDocId, String bstrVersion, Object& pvarAttachmentNames, Object& pvarAttachmentContents, Object& pvarProperties, Boolean bCheckOut, Boolean bCheckin,
    Boolean bMigration, Boolean bPublish, String bstrFileName, ISP2DSafeArrayWriter pListDataValidationCallback, ISP2DSafeArrayWriter pRestrictInsertCallback, ISP2DSafeArrayWriter pUniqueFieldCallback)
    System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'AllUserDataJunctions_PK'. Cannot insert duplicate key in object 'dbo.AllUserDataJunctions'.
    The duplicate key value is (21b5edcc-6e2d-421f-ad08-5a9e275add8a, 0x, 0, 10724c04-dcbb-4f02-af40-e19a694d015c, a558cc06-6f8a-408d-a1f6-f4b712d68881, 4096, 1, 4e405c39-8677-4ba0-8901-2ca4fa273461, 0).  The statement has been terminated.      at
    System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)      at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)      at System.Data.SqlClient.TdsParser.Run(RunBehavior
    runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)      at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()      at System.Data.SqlClient.SqlDataReader.get_MetaData()
         at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)      at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior
    runBehavior, Boolean returnStream, Boolean async)      at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)      at
    System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)      at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)  
       at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)      at Microsoft.SharePoint.Utilities.SqlSession.ExecuteReader(SqlCommand command, CommandBehavior behavior, SqlQueryData monitoringData, Boolean retryForDeadLock)
    at Microsoft.SharePoint.SPSqlClient.ExecuteQueryInternal(Boolean retryfordeadlock)    
     at Microsoft.SharePoint.SPSqlClient.ExecuteQuery(Boolean retryfordeadlock)    
     at Microsoft.SharePoint.Library.SPRequestInternalClass.AddOrUpdateItem(String bstrUrl, String bstrListName, Boolean bAdd, Boolean bSystemUpdate, Boolean bPreserveItemVersion, Boolean bPreserveItemUIVersion, Boolean bUpdateNoVersion, Int32&
    plID, String& pbstrGuid, Guid pbstrNewDocId, Boolean bHasNewDocId, String bstrVersion, Object& pvarAttachmentNames, Object& pvarAttachmentContents, Object& pvarProperties, Boolean bCheckOut, Boolean bCheckin, Boolean bMigration, Boolean bPublish,
    String bstrFileName, ISP2DSafeArrayWriter pListDataValidationCallback, ISP2DSafeArrayWriter pRestrictInsertCallback, ISP2DSafeArrayWriter pUniqueFieldCallback)    
     at Microsoft.SharePoint.Library.SPRequest.AddOrUpdateItem(String bstrUrl, String bstrListName, Boolean bAdd, Boolean bSystemUpdate, Boolean bPreserveItemVersion, Boolean bPreserveItemUIVersion, Boolean bUpdateNoVersion, Int32& plID,
    String& pbstrGuid, Guid pbstrNewDocId, Boolean bHasNewDocId, String bstrVersion, Object& pvarAttachmentNames, Object& pvarAttachmentContents, Object& pvarProperties, Boolean bCheckOut, Boolean bCheckin, Boolean bMigration, Boolean bPublish,
    String bstrFileName, ISP2DSafeArrayWriter pListDataValidationCallback, ISP2DSafeArrayWriter pRestrictInsertCallback, ISP2DSafeArrayWriter pUniqueFieldCallback)    
     at Microsoft.SharePoint.SPListItem.AddOrUpdateItem(Boolean bAdd, Boolean bSystem, Boolean bPreserveItemVersion, Boolean bNoVersion, Boolean bMigration, Boolean bPublish, Boolean bCheckOut, Boolean bCheckin, Guid newGuidOnAdd, Int32&
    ulID, Object& objAttachmentNames, Object& objAttachmentContents, Boolean suppressAfterEvents, String filename, Boolean bPreserveItemUIVersion)    
     at Microsoft.SharePoint.SPListItem.UpdateInternal(Boolean bSystem, Boolean bPreserveItemVersion, Guid newGuidOnAdd, Boolean bMigration, Boolean bPublish, Boolean bNoVersion, Boolean bCheckOut, Boolean bCheckin, Boolean suppressAfterEvents,
    String filename, Boolean bPreserveItemUIVersion)    
     at Microsoft.SharePoint.SPListItem.Update()    
     at BV.PEL.BL.Common.PublishProject(SPListItem sourceItem, Boolean isFromPublish, SPWeb web, SPSite systemSite, SPFieldUserValueCollection adminGroup, String strComments)    
     at BV.PEL.Portal.WebParts.OneBVProjectInformation.OneBVProjectInformationUserControl.buttonApprove_Click(Object sender, EventArgs e)    
     at System.Web.UI.WebControls.Button.OnClick(EventArgs e)    
     at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)    
     at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)    
     at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)    
     at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)    
     at System.Web.UI.Page.ProcessRequest()    
     at System.Web.UI.Page.ProcessRequest(HttpContext context)    
     at ASP.BLANKWEBPARTPAGE_ASPX_1653093133.ProcessRequest(HttpContext context)    
     at Microsoft.SharePoint.Publishing.TemplateRedirectionPage.ProcessRequest(HttpContext context)    
     at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()    
     at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)    
     at System.Web.HttpApplication.PipelineStepManager.ResumeSteps(Exception error)    
     at System.Web.HttpApplication.BeginProcessRequestNotification(HttpContext context, AsyncCallback cb)    
     at System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context)    
     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr managedHttpContext, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)    
     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr managedHttpContext, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)    
     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr managedHttpContext, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)    
     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr managedHttpContext, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)

  • Unique constraint fired when updating in MERGE statement.

    Hi guys
    I have an issue which I am unable to resolve. Would appreciate any help on this. The data setup and the scenario is as below.
    SQL*Plus: Release 10.2.0.1.0 - Production on Wed May 4 11:46:02 2011
    Copyright (c) 1982, 2005, Oracle.  All rights reserved.
    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bit Production
    With the Partitioning, OLAP and Data Mining options
    SQL>
    create table table_1
    (id number,
    id_name varchar2(20));
    Alter table table_1 add primary key(id);
    create table table_2
    (id number,
    id_name varchar2(20));
    insert into table_2 values (1, 'id_1');
    insert into table_2 values (2, 'id_2');
    insert into table_2 values (1, 'id_1_upd');
    SQL> select * from table_1;
    no rows selected
    SQL> select * from table_2;
            ID ID_NAME
             1 id_1
             2 id_2
             1 id_1_upd
    SQL>
    SQL>  merge into table_1 target
      2   using (select id,
      3                 id_name
      4            from table_2) source
      5   on (source.id = target.id)
      6   when matched then
      7      update set target.id_name = source.id_name
      8   when not matched then
      9      insert(id,
    10             id_name)
    11      values(source.id,
    12             source.id_name);
    merge into table_1 target
    ERROR at line 1:
    ORA-00001: unique constraint (SYS_C00137508) violated
    SQL> ed
    Wrote file afiedt.buf
      1  select constraint_type, table_name, status
      2*   from user_constraints where constraint_name = 'SYS_C00137508'
    SQL> /
    C TABLE_NAME                     STATUS
    P TABLE_1                        ENABLEDCan someone please help me in resolving this as the actual code that I am developing has the same setup and I am constantly getting this error. So long as the same record does not come up in the "source" table, MERGE does either an update or an insert.
    But as soon a "duplicate" record comes up for updation, I am getting the unique constraint error.
    Thanks
    - K.B.

    Dear,
    ERROR at line 1:
    ORA-00001: unique constraint (SYS_C00137508) violatedYou need to think about two things
    (a) read consistency : what was the situation of table_1 when the maching clause has been initially evaluated ; there were 0 rows matching which means the merge operation will be all insert
    (b) your matching clause has a problem : the join column must be unique in both tables otherwise the merge will be ambigous. You don't have a unique key on the source table
    (c) think that the merge operation will never insert id =1 and then update id = 1 within the same operation. This will never happen
    Hope this helps
    Mohamed Houri

  • APEX DB: Not accepting the constraint ON UPDATE CASCADE

    Hi
    My schema tables is not accepting the ON UPDATE CASCADE constraint as it was accepting the ON DELETE CASCADE constraint. My use case is to update the records in the child tables, when a PK of parent table is modified/updated. Please help.
    Thanks
    Bhavesh

    Bavesh,
    Boy this question could spark a huge debate about relational theory and the merits of allowing the update of a primary key... But instead of stirring the pot, I'll answer your question. :-)
    Unfortunately Oracle does not support the ON UPDATE CASCADE constraint that PostgreSQL and other databases do.
    You might look at [this discussion|http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:5773459616034] on ASK TOM where he talks about the merits and references a couple ways you can achieve similar things in Oracle.
    Hope That Helps,
    - Doug -
    http://sumnertech.com/

  • Unique constraint ERROR How to update the task order customly?

    I am using DAC to load data from Siebel database into Oracle Business Analytic Data Warehouse for BI Apps. Now we encounter a question. I need some help.
    When I run current execute plan, the Custom_shyy_SIL_ActivityFact is failured.Beause the *'unique constraint (SHYY_OLAP_DEV.W_ACTIVITY_F_U1) violated'* ORA_00001 ERROR. I analyse this question.At last, I think this question is caused with some below reason.
    My custom execute plan include some Update Dimension from Dimension tasks. They are SIL_EmployeeDimension_SCDUpdate and SIL_ProductDimension_SCDUpdate and so no. that tasks that marked Update Dimension from Dimension run before the Custom_shyy_SIL_ActivityFact. And, in the w_product_d one integration_id corresponding with two records, but the curent_flag ='Y' recored is only. Now ,I Think the SDCU Task is run before the Load fact tack. I discoved it does't work. please help me !

    Hey
    When Doing a full Load through DAC it drops all the unique indexes and then inserts the data and recreates the indexes again.The Index Creation fails if there are duplicate rows (Rows with same integration_id).
    So start Checking the Data right from the Source Level.
    First check the Source (do this using the integration_id thats repeating,Go through the informatica Mappings(ETL Mappings).
    If its Fine there Come to the Staging Level and Check for Duplicate Columns.
    Then Check in the final Table for Duplicate records.
    My Guess is that you are having duplicate rows at the Source level.
    If your are using informatica try using distinct for the SQL in the Source Qualifier(think that should block any duplicate records).
    Update here If you are able to solve this.
    Thanks
    Hemanth

Maybe you are looking for