Primary key violation when inserting records with insert_identity and ident_current+x

My problem is this: I have data in a couple of temporary tables including
relations (one table referencing records from another table by using
temporary keys).
Next, I would like to insert the data from the temp tables to my productive tables which have the same structure but their own identity keys. Hence, I need to translate the 'temporary' keys to regular identity keys in my productive tables.
This is even more difficult because the system is highly concurrent, i.e. multiple sessions may try to insert
data that way simultaneously.
So far we were running the following solution, using a combination of
identity_insert and ident_current:
create table doc(id int identity primary key, number varchar(100))
create table pos (id int identity primary key, docid int references doc(id), qty int)
create table #doc(idx int, number varchar(100))
create table #pos (docidx int, qty int)
insert #doc select 1, 'D1'
insert #doc select 2, 'D2'
insert #pos select 1, 10
insert #pos select 1, 12
insert #pos select 2, 32
insert #pos select 2, 9
declare @docids table(ID int)
set identity_insert doc on
insert doc (id,number)
output inserted.ID into @docids
select ident_current('doc')+idx,number from #doc
set identity_insert doc off
-- Since scope_identity() is not reliable, we get the inserted identity values this way:
declare @docID int = (select min(ID) from @docids)
insert pos (docid,qty) select @docID+docidx-1, qty from #pos
Since the request to ident_current() is located directly in the insert statement, we always have an implicit transaction which should be thread safe to a certain extend.
We never had a problem with this solution for years until recently when we were running in occasional primary key violations. After some reasearch it turned out, that there were concurrent sessions trying to insert records in this way.
Does anybody have an explanation for the primary key violations or an alternative solution for the problem?
Thank you
David

>> My problem is this: I have data in a couple of temporary tables including relations (one table referencing records [sic] from another table by using temporary keys [sic]). <<
NO, your problem is that you have no idea how RDBMS and SQL work. 
1. Rows are not anything like records; this is a basic concept.
2. Temp tables are how old magnetic tape file mimic scratch tapes. SQL programmers use CTEs, views, derived tables, etc. 
3. Keys are a subset of attributes of an entity, fundamental characteristics of them! A key cannot be temporary by definition. 
>> Next, I would like to insert the data from the temp tables to my production tables which have the same structure but their own IDENTITY keys. Hence, I need to translate the 'temporary' keys to regular IDENTITY keys in my productive tables. <<
NO, you just get worse. IDENTITY is a 1970's Sybase/UNIX dialect, based on the sequential file structure used on 16-bit mini computers back then. It counts the physical insertion attempts (not even successes!) and has nothing to with a logical data model. This
is a mag tape drive model of 1960's EDP, and not RDBMS.
>> This is even more difficult because the system is highly concurrent, i.e. multiple sessions may try to insert data that way simultaneously. <<
Gee, that is how magnetic tapes work, with queues. This is one of many reasons competent SQL programers do not use IDENTITY. 
>> So far we were running the following solution, using a combination of IDENTITY_INSERT and IDENT_CURRENT: <<
This is a kludge, not a solution. 
There is no such thing as a generic “id” in RDBMS; it has to be “<something in particular>_id” to be valid. You have no idea what the ISO-11179 rules are. Even worse, your generic “id” changes names from table to table! By magic, it starts as a “Doc”,
then becomes a “Pos” in the next table! Does it wind up as a “doc-id”? Can it become a automobile? A squid? Lady Gaga? 
This is the first principle of any data model; it is based on the Law of Identity; remember that from Freshman Logic 101? A data element has one and only one name in a model. 
And finally, you do not know the correct syntax for INSERT INTO, so you use the 1970's Sybase/UNIX dialect! The ANSI/ISO Standard uses a table consrtuctor: 
INSERT INTO Doc VALUES (1, 'D1'), (2, 'D2'); 
>> We never had a problem with this solution for years until recently when we were running in occasional PRIMARY KEY violations. After some research it turned out, that there were concurrent sessions trying to insert records [sic] in this way. <<
“No matter how far you have gone down the wrong road, turn around.” -- Turkish proverb. 
You have been mimicking a mag tape file system and have not written correct SQL. It has caught up with you in a way you can see. Throw out this garbage and do it right. 
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL

Similar Messages

  • Chaging primary key value when child record present

    Please tell me how to change the primary key value when it's child record is present.

    Well something like INSERT new primary key, UPDATE child records, DELETE old primary key would seem fairly obvious.
    Using deferrable constraints may make the process rather simpler.
    If on the other hand you are looking for UPDATE cascade functionality, Tom Kyte has an article regarding implementing this.
    http://asktom.oracle.com/tkyte/update_cascade/index.html

  • Issue with INSERT INTO, throws primary key violation error even if the target table is empty

    Hi,
    I am running a simple
    INSERT INTO Table 1 (column 1, column 2, ....., column n)
    SELECT column 1, column 2, ....., column n FROM Table 2
    Table 1 and Table 2 have same definition(schema).
    Table 1 is empty and Table 2 has all the data. Column 1 is primary key and there is NO identity column.
    This statement still throws Primary key violation error. Am clueless about this? 
    How can this happen when the target table is totally empty? 
    Chintu

    Nope thats not true
    Either you're not inserting to the right table or in the background some other trigger code is getting fired which is inserting into some table which causes a PK violation. 
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Primary key violation exception in auto increment column

    Hi All,
    I am facing one issue in Multi threaded environment.
    I am getting Primary key violation exception in auto increment column. I have a table and the primary key is the auto increment column, and I have a trigger which is populating this column.
    5 threads are running and inserting the data in the table and throwing Primary key violation exception randomly.
    create table example (
    id number not null,
    name varchar2(30)
    alter table example
    add constraint PK1example primary key (id);
    create sequence example_id_seq start with 1 increment by 1;
    create or replace trigger example_insert
    before insert on example
    for each row
    begin
    select example_id_seq.nextval into :new.id from dual;
    end;
    Any idea how to handle auto increment column(trigger) in Multi threaded environment??
    Thanks,

    user13566109 wrote:
    Thanks All,
    Problem was in approach; removed the trigger and placed a seq.nextval in insert query. It has resolved the issue.I very much suspect that that was not the issue.
    The trigger would execute for each insertion and the nextval would have been unique for each insertion (that's how sequences work in oracle), so that wouldn't have been causing duplicates.
    I suspect, more likely, that you had some other code somewhere that was using another sequence or some other method of generating the keys that was also inserting into the same table, so there was a conflict in the sources of the sequences being generated.
    The way you showed you had coded above, was a perfectly normal way to assign primary keys from a sequence, and is not a problem in a multi user/threaded environment.

  • How to pass values for compound primary keys for updating the record in db.

    i have a entity bean in my ejb with two primary keys to it...eg. roleid,rolename...
    when iam retriving the record i use only one primary key ...so again to modify and update he same record which i retrived is a pbm..
    i cannot set the values for the compoundpk,,,
    but i can do the update for the bean with single primary key..
    i need to know how to pass the values/parameters for the coumpound primary key in my update method...
    thanx in advance...
    Arjun.G

    I istantiated a object for the pk class and assign the values for the primary key fields...
    Arjun.G

  • Checking for duplicate primary keys on row inserts

    Checking for duplicate primary keys on row inserts
    I have a situation where I will be making bulk table inserts knowing that the primary key value will in some cases already exist. In this is the case I simply want to ignore the duplicate inserts.
    Should I be performing a sub-query on the table and using a statement like:
    where not exist in
    Or is there a cleaner way of discarding or checking for duplicates on insert.
    My concerns were mainly one of performance, as my routine will be inserting a few thousand rows in its operation.

    The MERGE commnad is a good option when a large percentage of the data will exist in the target because it is much more efficient to attempt to update then insert when the update affects zero rows than capture an error and convert it to an update.
    However, since in this case it would appear that only a few rows will alreadys exist and we want to ignore the duplicates when they exist then
    begin
    insert
    exception
    when dup_value_in_index then null;
    end
    would be the way to code this one. The bulk insert version has in 9.2 the ability to store the errors so that they can all be handled at once which means the rest of the array insert can work.
    HTH -- Mark D Powell --

  • Unique key violation i.e. primary key violation in JSF page

    Hi, I am using Jdeveloper 11.1.1.5.0 and working with adf fusion web application. I have created entity object and view object. In view object I have primary key and I have set it's type to DB sequence. THe problem is though the attribute is DB sequence. IN JSF page it show unique key violation i.e. primary key violation. Please help me

    So, do you have a trigger in the database that updates the value of the primary key? Or do you assign the value in some other way?
    You can check [url http://download.oracle.com/docs/cd/E16162_01/web.1112/e16182/toc.htm]the docs for information about the ways it can be done.

  • How to handle the unique primary key validation when is a multipart key !

    I dont know how to handle the primary key validation when the primary key is a multipart key.
    Besides would like to know how to catch the TooManyObjectsException in order to custom the default exception message.
    thank u.
    regards,
    Orlando Acosta

    Are you using EJB's, Toplink, or BC4J?
    Thanks,
    Rob
    Team JDev

  • How to insert records with LONG RAW columns from one table to another

    Does anybody know how to use subquery to insert records with columns of LONG RAW datatype from one table to another? Can I add a WHERE clause in the subquery statement? Thanks.

    Insert into ... Select statements are not supported for long or long raw. You will have to either use PL/SQL or convert your long raw to blobs.

  • When I record with my iSight camera, after a few seconds it stops recording and tell me there is "Dropfame" images. What do I have to make?

    When I record with my iSight camera, after a few seconds it stops recording and tell me there is "Dropfame" images. What do I have to make?
    A few weeks ago, my camera doesn't do that, but since 1-2 weeks it becomes impossible to record with it.

    Hi mstearns59,
    If you are having issues with the audio in a movie in iTunes and video playback issues I would suggest that you troubleshoot using the steps in this article - 
    Troubleshooting iTunes for Windows Vista or Windows 7 video playback performance issues
    Thanks for using Apple Support Communities.
    Best,
    Brett L 

  • Do I need to Create Primary Key Class for Entity beans with Local interface

    Do I need to Create Primary Key Class for Entity beans with Local interface?
    I have created my entity bean with the wizard in Sun One Studio and it does not create a primary key class for you.
    I thought that the primary key class was required. My key is made up of only one field.
    Anyone know the answer.
    Jim

    u dont need to create a primary key class for a entity bean.if ur table's primary key feild(int ,float) is a built in or primitive data type,then u dont need one.But if ur table has a primary key field which is non primitive (for example StudentID,ItemID etc)then u have to create a primary key class.
    hope this helps :-)

  • When I design with Muse and export as HTML Dreamweaver doesn't attach the style sheets. Any answers?

    When I design with Muse and export as HTML Dreamweaver doesn't attach the style sheets when I open the files with Dreamweaver. Essentially when I design with Muse the files don't render the same with Dreamweaver. Is this a bug? Any work arounds?

    Then you will have to install a local server and use live view.  It's not that DW isn't rendering it or isn't attaching it, it's that Muse decided to use server-side processing to include it which is ok for a CMS practice when you are combining stylesheets for better caching, but it really isn't ideal for a single style sheet.  This is a shortcoming of Muse and one of the reasons many professionals don't back the product at the moment.  That and you can't actually buy Muse, so unless you are on a subscription you don't have it.  It's trying to fill a void for those who don't want to invest in the professional design tools like Fireworks or Photoshop or Dreamweaver, but want a cross between them to make designs.  If you have invested in the subscription though and want a better way to make layouts I highly recommend coding it yourself and using Fireworks or Photoshop to do the layout for you.  There is an excellent tutorial on the devnet (3 parts) to show you how its done ( http://www.adobe.com/devnet/dreamweaver/articles/dw_fw_css_pt1.html ).  Once you start using Fireworks or Photoshop you will realize just how limited Muse is in design.

  • When im facetiming with someone and im watching a youtube video at the same time, the volume for the youtube video is lowered and the facetime volume stays the same, how can i change that?

    When im facetiming with someone and im watching a youtube video at the same time, the volume for the youtube video is lowered and the facetime volume stays the same, how can i change that?

    Have you ever even used skype on an iphone or ipod?  We tried it and there is no way to type to each other while you are video chatting.  You can do the typing during the video on a COMPUTER, but not on an iphone or ipod.

  • My ipod will only charge when i fiddle with it and hold it in a weird position, i've tried a 2 new chargers but i still have the same problem, any ideas what to do?

    my ipod will only charge when i fiddle with it and hold it in a weird position, i've tried a 2 new chargers but i still have the same problem, any ideas what to do?

    Not Charge
    - See:      
    iPod touch: Hardware troubleshooting
    iPhone and iPod touch: Charging the battery
    - Try another cable. (is this what you meant by charger?)
    - Try another charging source
    - Inspect the dock connector on the iPod for bent or missing contacts, foreign material, corroded contacts, broken, missing or cracked plastic.
    - Make an appointment at the Genius Bar of an Apple store.
    Apple Retail Store - Genius Bar                          

  • Problem with primary key violation in master-detail screens

    Hi,
    I found a problem/bug in master-detail screens in which the PK of the detail table consist of the PK of the master table and an additional column. E.g. a manually entered sequence 'in parent'.
    I will use the following simple scenario to explain the problem (it's easy to reproduce):
    PROJECT table
    # id (PK)
    * name
    PROJECT REQUIREMENTS table
    # prj_id (PK)
    # sequence_id (PK)
    * description
    Just create the BC EO, VO and AM and set both display properties of the prj_id attribute of the project requirements VO to hidden.
    Create a new screen in the application structure file in which you can select a project (table-form layout) and display the details (table layout) on the same page.
    With this basic setup you can generate the app to enter, update and delete projects and their requirements.
    The problem occurs if you have a project with a least 1 requirements stored in the database and you try to enter a second requirement with an existing sequence_id within the project. This is an use case in which a end-user enters wrong data.
    So assume we have in the database:
    prj_id sequence_id description
    ====== =========== ===========
    1 1 req1
    and the end-user enters (prj_id is entered automatically as it's not displayed):
    1 1 req2 >> user should have enterd sequence_id 2...
    Step 1. If you try to save an error will be displayed:
    JBO-25013: Too many objects match the primary key oracle.jbo.Key[227300 1 ].
    And the sequnece_id is emptied automatically.
    Step 2. So the end-user re-enters the sequence_id but fills in 2 now and saves.
    Another error is displayed: JBO-27014 sequence_id in AppModule is required
    How strange? Everything is filled in already.
    Step 3. If you just hit save again (without changing anything) you got a transaction completed successfully.
    I checked the logfiles and noticed an exception during after executing step 2.
    oracle.jbo.AttrValException: JBO-27014: Attribute SequenceId in AppModule.ProjectRequirementsView2 is required     at oracle.jbo.AttrValException.<init>(AttrValException.java)     at oracle.jbo.server.JboMandatoryAttributesValidator.validate(JboMandatoryAttributesValidator.java)     at oracle.jbo.server.EntityDefImpl.validate(EntityDefImpl.java:2051)     at oracle.jbo.server.EntityImpl.validateEntity(EntityImpl.java:1373)     at mypackage1.ProjectRequirementsImpl.validateEntity(JwTekeningnummerImpl.java:273)     at oracle.jbo.server.EntityImpl.validate(EntityImpl.java:1508)     at oracle.jbo.server.EntityImpl.validateChildren(EntityImpl.java:1232)     at oracle.jbo.server.EntityImpl.validateEntity(EntityImpl.java:1339)     at oracle.jbo.server.EntityImpl.validate(EntityImpl.java:1508)     at oracle.jbo.server.DBTransactionImpl.validate(DBTransactionImpl.java:3965)     at oracle.adf.model.bc4j.DCJboDataControl.validate(DCJboDataControl.java:967)     at oracle.adf.model.binding.DCBindingContainer.validateInputValues(DCBindingContainer.java:1683)     at oracle.jheadstart.view.adfuix.JhsInitModelListener.validateInputValues(JhsInitModelListener.java:193)     at oracle.jheadstart.view.adfuix.JhsInitModelListener._doModelUpdate(JhsInitModelListener.java:166)     at oracle.jheadstart.view.adfuix.JhsInitModelListener.eventStarted(JhsInitModelListener.java:92)     at oracle.cabo.servlet.AbstractPageBroker._fireUIXRequestEvent(Unknown Source)     at oracle.cabo.servlet.AbstractPageBroker.handleRequest(Unknown Source)     at oracle.cabo.servlet.ui.BaseUIPageBroker.handleRequest(Unknown Source)     at oracle.adf.controller.struts.actions.StrutsUixLifecycle$NonRenderingPageBroker.handleRequest(StrutsUixLifecycle.java:325)     at oracle.cabo.servlet.PageBrokerHandler.handleRequest(Unknown Source)     at oracle.adf.controller.struts.actions.StrutsUixLifecycle._runUixController(StrutsUixLifecycle.java:215)     at oracle.adf.controller.struts.actions.StrutsUixLifecycle.processUpdateModel(StrutsUixLifecycle.java:106)     at oracle.jheadstart.controller.strutsadf.action.JhsStrutsUixLifecycle.processUpdateModel(JhsStrutsUixLifecycle.java:140)     at oracle.adf.controller.struts.actions.DataAction.processUpdateModel(DataAction.java:317)     at oracle.jheadstart.controller.strutsadf.action.JhsDataAction.processUpdateModel(JhsDataAction.java:622)     at oracle.adf.controller.struts.actions.DataAction.processUpdateModel(DataAction.java:508)     at oracle.adf.controller.lifecycle.PageLifecycle.handleLifecycle(PageLifecycle.java:112)     at oracle.adf.controller.struts.actions.StrutsUixLifecycle.handleLifecycle(StrutsUixLifecycle.java:70)     at oracle.adf.controller.struts.actions.DataAction.handleLifecycle(DataAction.java:223)     at oracle.jheadstart.controller.strutsadf.action.JhsDataAction.handleLifecycle(JhsDataAction.java:389)     at oracle.adf.controller.struts.actions.DataAction.execute(DataAction.java:155)     at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)     at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)     at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1485)     at oracle.jheadstart.controller.strutsadf.JhsActionServlet.process(JhsActionServlet.java:127)     at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:527)     at javax.servlet.http.HttpServlet.service(HttpServlet.java:765)     at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)     at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)     at oracle.security.jazn.oc4j.JAZNFilter.doFilter(Unknown Source)     at com.evermind.server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:16)     at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:239)     at com.evermind.server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:20)     at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:239)     at com.evermind.server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:20)     at oracle.jheadstart.controller.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java)     at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:645)     at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:322)     at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:790)     at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:270)     at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:112)     at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:192)     at java.lang.Thread.run(Thread.java:534)
    This also explains why I got a error message within the application at step 2, but not an expected error message!
    From the logfile I can see something is going wrong in the oracle.jbo.server.EntityImpl.validateEntity method.
    To get more insight what was goning on I overridden the validateEntity method in my VO Impl class:
    protected void validateEntity()
    System.out.println("MARCEL>> sequenceId=" + getSequenceId());
    System.out.println("MARCEL>> description=" + getDescription());
    super.validateEntity();
    In step 1 the validateEntity is not called.
    In step 2 the sequeceId = null (and description = reg2)
    I expected the sequeceId to be 2 now as I entered this. Furthermore if I look at the (JhsActionServlet) request parameters in the log, I can see that the value of the sequenceId was 2. I guess something is going wrong at this point in converting the request parametes to the EO.
    In step 3 the sequeceId = 2 (as expected)
    Note that I'm using the evaluation copy version of JHeadstart 10.1.2.
    If this was patched in any later build, could you please tell which changes I have to make to the JHS sources to solve this problem.
    Regards,
    Marcel

    Marcel,
    I cannot reproduce this in version 10.1.2.2. We did not "fix" this, although changes in the runtime might have fixed this "silently". I suggest you upgrade to 10.1.2.2 and see whether you still get the error.
    Steven Davelaar,
    JHeadstart Team.

Maybe you are looking for

  • How to play a slideshow (with movies) from Iphoto to Apple TV second gen

    Hi, Does anyone know how to play a slideshow with movies, that I normally play perfect with Iphoto (I even can add music)to let it stream to the Apple tv second gen? So I have some movies on Imac from a holiday in Egypt and Iphoto alows me let it pla

  • Screen modification's.

    Hiring Action: 1.     The drop-down list for reason for hiring includes 'no reason', 'new position' and 'vacancy'.  She wanted 'Additional Requirement' to replace 'no reason'. 2.On the 'Additional Personal Data' infotype, the systems accepts only 'No

  • File transfers - ASC vs BIN ?

    Hi everyone ! Can somebody explain to me the "technical" difference between transfering files in ASC vs BIN mode. I use TCode CG3Y to download files from the SAP server to my PC and I noticed that ASC mode truncates (after ?? characters on the same l

  • About query generator.

    SAP B1 2007 A PL46 Hi All, I have many questions about query generator : 1. It is possible to use or to call a stored procedure ? If yes, how can we implement this ? 2. I try to use this query : declare @commercial integer set @commercial = [%0] decl

  • Recovering photos from my dead iMac

    My G4 Flat panel iMac failed recover from a power cut some months ago and, although sad, was a good excuse to buy a G5. However, this has left many photos and tunes stranded in the hulk. Buying a new power unit to recover the media is rather expensiv