SQL- Obtaining primary key in newly inserted data

Anyone know of an easy way to obtain a primary autonumber key from a newly inserted record ??
Martin

"Martin Eder" wrote:
>This is a multi-part message in MIME format.>>------=_NextPart_000_0010_01C07707.14E4F6C0>Content-Type:
text/plain;> charset="iso-8859-1">Content-Transfer-Encoding: quoted-printable>>Anyone
know of an easy way to obtain a primary autonumber key from a =>newly inserted
record ??>>Martin>>------=_NextPart_000_0010_01C07707.14E4F6C0>Content-Type:
text/html;> charset="iso-8859-1">Content-Transfer-Encoding: quoted-printable>>
HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">>>content=3D"text/html; =>charset=3Diso-8859-1">>name=3DGENERATOR>>>>>
face=3DArial size=3D2>Anyon
e know of an easy way to obtain a =>primary=20>autonumber
key from a newly inserted record ??>
size=3D2> >Martin>>------=_NextPart_000_0010_01C07707.14E4F6C0-->
Yes, for MS SQL7 modify the EasySQL vi to execute the SQL command 'SELECT
@@IDENTITY' the query results will contain the identity of the inserted row.

Similar Messages

  • 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 --

  • 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

  • Primary Key Conflicts While Inserting Rows

    Hi,
    I am inserting some rows into a table which has primary key constraints on columns 1,2,3. I have set the key columns in my program to 1,2,3. When I try to insert a row it throws a syncresolver exception stating that there is a key conflict. But i don't understand why it is doing this because there is no conflict. I can remove the primary key constraints off the sql table (but still leave them on in the program) and it will insert everything correctly.
    Any ideas?
    Thanks

    Using SQL Server 2005 Drivers.
    import java.sql.*;
    import javax.sql.rowset.*;
    import com.sun.rowset.*;
    public class TestDB {
         public static void main(String[] args){
              String connectionUrl = "jdbc:sqlserver://DBSERVER;DatabaseName=fTrack;user=sa;password=1234";
              // Declare the JDBC objects.
              Connection con = null;
              CachedRowSet crs = null;
              int keys[] = {1,2,3};
              try {
                   // Establish the connection.
                   Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                   con = DriverManager.getConnection(connectionUrl);
                   // Create and execute an SQL statement that returns some data.
                   String SQL = "SELECT * FROM pt_OMS_Data WHERE Switch=4";
                   crs = new CachedRowSetImpl();
                   crs.setCommand(SQL);
                   crs.execute(con);
                   crs.setKeyColumns(keys);
                   crs.beforeFirst();
                   crs.moveToInsertRow();
                   crs.updateInt(1, 5);
                   crs.updateTimestamp(2, Timestamp.valueOf("2007-07-20 00:00:00"));
                   crs.updateInt(3, 0);
                   crs.insertRow();
                   crs.moveToCurrentRow();
                   crs.moveToInsertRow();
                   crs.updateInt(1, 5);
                   crs.updateTimestamp(2, Timestamp.valueOf("2007-07-20 00:00:00"));
                   crs.updateInt(3, 1);
                   crs.insertRow();
                   crs.moveToCurrentRow();
                   crs.acceptChanges(con);
              // Handle any errors that may have occurred.
              catch (Exception e) {
                   e.printStackTrace();
              } finally {
                   if (crs != null)
                        try {
                             crs.close();
                        } catch (Exception e) {
                   if (con != null)
                        try {
                             con.close();
                        } catch (Exception e) {
    }Layout of DB:
    Switch Date BSC ColA ColB ColC
    Switch, Date, and BSC are the PKs.
    Switch is type Int, Date is type datetime, BSC is type int
    Here is the error which i receive:
    javax.sql.rowset.spi.SyncProviderException: 4 conflicts while synchronizing
         at com.sun.rowset.internal.CachedRowSetWriter.writeData(Unknown Source)
         at com.sun.rowset.CachedRowSetImpl.acceptChanges(Unknown Source)
         at com.sun.rowset.CachedRowSetImpl.acceptChanges(Unknown Source)
         at TestDB.main(TestDB.java:39)
    I inserted the exact same data manually into the DB and it works fine.
    By the way, the program inserts the first row, but not the second. Based on my trials with the original program I am working on the syncproviderexception handler seems to have a conflict on insert row on Switch column. This is why I believe java is not interpreting the PKs as a group but rather as individually.
    Message was edited by:
    bce_developer

  • Urgent - ESB: DB Adapter with composite primary keys no returning any data

    I have a DB Adapter in the ESB that inserts/updates/selects data to/from a table with 2 columns as primary keys, but table has several columns.
    1. Initially, the db table had constraints for the composite primary key, The DB adapter had valid data coming in, but no result data.
    2. Then I removed the db constraints on the composite primary key, and selected the 2 columns in the DB adapter wizard. Still, valid data is going in, since I am outputing to a file prior to call this node, but no result data is appearing. The result XML is empty.
    Do I need to do something in Toplink for this?
    The table spec is below. the ACCT_FIELD and ACCT_CODE columns make up the composite primary key.
    CREATE TABLE AFF_DATA_SYNC
    ACCT_FIELD NUMBER NOT NULL,
    ACCT_CODE VARCHAR2(16) NOT NULL,
    ACCT_EXISTS_FLAG VARCHAR2(1),
    SAVE_ACCT_SEG_XML CLOB,
    LAST_UPDATE_DATE DATE
    The following xml is the request to the DB adapter:
    <top:AffDataSyncReadDBAdapterSelect_accountField_accountCodeInputParameters xmlns:top="http://xmlns.oracle.com/pcbpel/adapter/db/top/AffDataSyncReadDBAdapter">
    <top:accountField>8</top:accountField>
    <top:accountCode>0003888</top:accountCode>
    </top:AffDataSyncReadDBAdapterSelect_accountField_accountCodeInputParameters>
    Log output:
    JCA: esb:///ESB_Projects/STRIPES-AFF-Data-Intg_AFF-Data-Integration/AffDataSyncReadDBAdapter.wsdl [ AffDataSyncReadDBAdapter_ptt::AffDataSyncReadDBAdapterSelect_accountField_accountCode(AffDataSyncReadDBAdapterSelect_accountField_accountCode_inparameters,Af
    DataSyncWipCollection) ] - No XMLRecord headers provided
    JCA: <oracle.tip.adapter.db.DBInteraction executeOutboundRead> Executing query with arguments [8, 0003917]
    JCA: <oracle.tip.adapter.db.TopLinkLogger log> SELECT ACCT_FIELD, ACCT_CODE, ACCT_EXISTS_FLAG, SAVE_ACCT_SEG_XML, LAST_UPDATE_DATE FROM
    AFF_DATA_SYNC_WIP WHERE ((ACCT_FIELD = ?) AND (ACCT_CODE = ?))
    bind => [8, 0003888]
    JCA: <oracle.tip.adapter.db.DBInteraction executeOutboundRead> Read the following objects: []
    Message was edited by:
    user589357
    Message was edited by:
    user589357
    Message was edited by:
    user589357
    Message was edited by:
    user589357

    The Toplink has no errors. Now I changed my table with only a single primary key, but for some reason, I am still getting no data.
    JDeveloper 10.1.3.3 / SOA Suite (only using ESB) 10.1.3.3 with Oracle DB 10g 10.2.0.3.
    1. What does No XMLRecord headers found mean?
    2. Notice the last log item; Read ... []
    Here are the log contents:
    Invoking next service "AffDataSyncReadDBAdapterSelect_recordId" with payload :
    <top:AffDataSyncReadDBAdapterSelect_recordIdInputParameters xmlns:top="http://xmlns.oracle.com/pcbpel/adapter/db/top/AffDataSyncReadDBAdapter">
    <top:recordId>80003888</top:recordId>
    </top:AffDataSyncReadDBAdapterSelect_recordIdInputParameters>
    JCA: esb:///ESB_Projects/STRIPES-AFF-Data-Intg_AFF-Data-Integration/AffDataSyncReadDBAdapter.wsdl [ AffDataSyncReadDBAdapter_ptt::AffDataSyncReadDBAdapterSelect_recordId(AffDataSyncReadDBAdapterSelect_recordId_inparameters,AffDataSyncWipCollection)
    ] - No XMLRecord headers provided
    JCA: esb:///ESB_Projects/STRIPES-AFF-Data-Intg_AFF-Data-Integration/AffDataSyncReadDBAdapter.wsdl [ AffDataSyncReadDBAdapter_ptt::AffDataSyncReadDBAdapterSelect_recordId(AffDataSyncReadDBAdapterSelect_recordId_inparameters,AffDataSyncWipCollection)
    ] - Starting JCA LocalTransaction
    JCA: esb:///ESB_Projects/STRIPES-AFF-Data-Intg_AFF-Data-Integration/AffDataSyncReadDBAdapter.wsdl [ AffDataSyncReadDBAdapter_ptt::AffDataSyncReadDBAdapterSelect_recordId(AffDataSyncReadDBAdapterSelect_recordId_inparameters,AffDataSyncWipCollection)
    ] - Invoking JCA Outbound Interaction
    JCA: <oracle.tip.adapter.db.DBInteraction executeOutboundRead> executing the NamedQuery: AffDataSyncReadDBAdapter.AffDataSyncWip.AffDataSyncReadDBAdapterSelect
    JCA: <oracle.tip.adapter.db.DBInteraction executeOutboundRead> Parsing header record element.
    JCA: <oracle.tip.adapter.db.TopLinkLogger log> client acquired
    JCA: <oracle.tip.adapter.db.DBInteraction executeOutboundRead> Executing query with arguments [80003888]
    JCA: <oracle.tip.adapter.db.TopLinkLogger log> SELECT RECORD_ID, ACCT_FIELD, ACCT_CODE, ACCT_EXISTS_FLAG, SAVE_ACCT_SEG_XML, LAST_UPDATE_DATE
    FROM AFF_DATA_SYNC_WIP WHERE (RECORD_ID = ?)
    bind => [80003888]
    JCA: <oracle.tip.adapter.db.DBInteraction executeOutboundRead> Read the following objects: []
    Message was edited by:
    user589357
    Message was edited by:
    user589357

  • Primary key generation by insert trigger.

    I have a table and wish to automatically create a unique sequence number for use as the primary key.
    In PL/SQL I do something like this:
    create sequence personnel_seq;
    create or replace trigger personnel_insert
    before insert on personnel
    for each row
    declare seqNo NUMBER;
    begin
    select personnel_seq.NextVal into seqNo from dual;
    :new.vc_personnel_reference := seqNo;
    end personnel_insert;
    column personnel.vc_personnel_reference is the primary key of table personnel, and not null.
    What's the recommended way to do something similar in BC4J?
    At present I'm using the trigger but BC4J doesn't know it exists, and insists on a value for vc_personnel_reference being provided. It also insists on adding the primary key to the ViewObject's attributes.
    I can provide a dummy value in ViewObjectRowImpl.insertRow() but this seems cumbersome.
    Is there a better way?
    In fact can I do this kind of thing entirely in BC4J without the trigger?
    Tony.

    But be carefull with DBSequences.
    There's a "problem" because the DBSequencs is a Domain and a "domained" field is not equal to any other field.
    In that case if have an Entity with Id = 1 (where d comes out from a DbSequence) and You look for Id = n where n is a Number containing 1, You will not find Your record !!!
    As 9.0.2.; I don't know in 9.0.3.
    Bye
    Tullio

  • SQL Server - primary key constraint modify

    Hi,
    I have a table with many records. I wanted to modify the primary key constraint. The only way to alter the primary key constraint is to drop and create again. Please let me if it is right.
    Can we create primary key constraint with NoCheck. Since we have lots of records in our table, creating primary key constraint takes more time because it is checking the existing data. Please provide your comments.
    Thanks.

    >>I have a table with many records. I wanted to modify the primary key constraint. The only way to alter the primary key constraint is to drop and create again. Please let me if it is right.
    http://technet.microsoft.com/en-us/library/ms181043(v=sql.105).aspx
    Note
    To modify a PRIMARY KEY constraint, you must first delete the existing PRIMARY KEY constraint and then re-create it with the new definition.
    >>Can we create primary key constraint with NoCheck. Since we have lots of records in our table, creating primary key constraint takes more time because it is checking the existing data. Please provide your comments.
    http://msdn.microsoft.com/en-IN/library/ms188066.aspx
    When FOREIGN KEY or CHECK constraints are added, all existing data is verified for constraint violations unless the WITH
    NOCHECK option is specified. If any violations occur, ALTER TABLE fails and an error is returned. When a new PRIMARY KEY or UNIQUE constraint is added to an existing column, the data in the column or columns must be unique. If duplicate values are found, ALTER
    TABLE fails. The WITH NOCHECK option has no effect when PRIMARY KEY or UNIQUE constraints are added.
    Satheesh
    My Blog |
    How to ask questions in technical forum

  • ?Trigger to return primary key value after insert"

    Ok, so I'm a newbie to oracle. I was hoping someone could tell
    me how I can get the value of a field after insertion. I
    created a sequence and a trigger to autoincrement the primary
    key. I figured out that select @@Identity does not work. So
    I'm trying to figure out how to return the primary key value of
    just inserted record.
    Any help or suggestions would be really appreciated.
    thanks matt

    I have 3 tables - master, detail and collector.
    when a record is inserted into the collector table - I want to fire a trigger and insert the value of "collector.a_test", "collector.b_test" into "master.test" and "detail.test" respectively.
    I want to create an after/insert trigger on the collector table to accomplish this. I tried to implement the example listed in previous message (see below) *** BUT **** I get a PLS-00103 error - "Encountered the symbol "A_ID" when expecting one of the following: :=. ( @ %;
    Note: master, detail and collector have before insert trigger/sequence that assigns their PK values.
    master has 2 columns - a_id (number PK), a_test (varchar2(255))
    detail has 3 columns - b_id (number PK), b_test (varchar2(255)), aa_id (number FK)
    collector has 3 columns - c_id (number PK), a_test (varchar2(255)), b_test (varchar2(255))
    as in;
    create or replace trigger wf.c_a_b_insert
    after insert on wf.collector
    referencing old as old new as new
    for each row
    declare
    aa_id master.a_id%type;
    begin
    insert into master (a_test) values(:new.a_test);
    returning a_id into aa_id;
    /* now insert into detail and get the FK value from aa_id */
    end;
    What am I doing wrong and how can I fix this?
    Thanks much!
    Bill G...

  • Primary Key Multiple Column with Date - parameter issue

    All,
    I am having an issue that I cannot find the answer to. I have looked high and low to no avail. Please help.
    The issue at hand is that I have a table that has a multiple column primary key and one of the columns happens to be a date and the other is a string. I have a basic search and I want an update picture in the results table that the users can click on and go to a different page to update that record. The issue is when I fire an action based on the update picture I also want to set parameters based on the record that I selected. So I set the string parameter and that works fine. The issue is with the date. When i set the date parameter it works but it chops off the timestamp. Later when I try to get this parameter 'pageContext.getParameter("dateParameter");' it will bring in a date like 15-Dec-2008 but I need the entire date and timestamp (i.e. 15-Dec-2008 10:20:33) to correctly identify the record.
    Please help!
    Thanks,
    Colby J

    Hi
    since every parameter go in url as a string format so u will never get the date parameter with complete timestamp,the solution would de
    1.) Set a fire action on update picture,give its event name as "update",
    2.) clicking on update picture will fire this event .
    3.) in processFormrequest method of controller
    OAApplicationModule am = pageContext.getApplicationModule(webBean);
    if ("update".equals(pageContext.getParameter("event")))
    // this will give the select row where update is clicked
    String rowReference = pageContext.getParameter(OAWebBeanConstants.EVENT_SOURCE_ROW_REFERENCE);
    VORowImpl row = (EmployeeSummaryVORowImpl)am.findRowByRef(rowReference);
    Timestamp sdateVal=(String)row.getAttribute("Date value");
    // this will transfer the values to next page
    pageContext.putTransactionTransientValue("transferdvalue",sdateVal);
    // and in the next page u can get the value like this
    timestamp getDateVal=pageContext.getTransactionTransientValue("transferdvalue"l);
    hope this will resolve your issue,Please let me know if u face any issue
    thanx
    Pratap

  • SQL API. Database corrupted when inserting data?

    Hi, I have a working sqlite application I was going to migrate to BerkeleyDB to try and solve some locking issues. However I am having some trouble creating the database.
    I downloaded the windows pre-built binaries and created my schema with dbsql.exe. The DDL worked fine and running db_verify reported no errors. However after I inserted about twenty rows of data using a SQL script of INSERT commands db_verify reported about ten "out-of-order key" messages. There are no INSERT triggers in the DDL. I tried running the INSERTs as single commands, and the out-of-order key messages appeared after about ten rows of data. A bit of googling only revealed that these errors often occur when using tools linked to different BerkelyDB versions. I have never had any version of BerkeleyDB installed before.
    I then downloaded the BerkeleyDB source and built the binaries myself. I again created the schema - no problems, inserted about twenty rows - errors the same as before. When running db_recover the error messages are as below:
    C:\Program Files (x86)\Oracle\Berkeley DB 11gR2 5.1.25\bin\SFTPVT.BDB-journal>..\db_recover.exe
    db_recover.exe: Ignoring log file: log.0000000001: magic number 1563f1a3, not 40988
    db_recover.exe: Invalid log file: log.0000000001: Invalid argument
    db_recover.exe: PANIC: Invalid argument
    db_recover.exe: process-private: unable to find environment
    db_recover.exe: DB_ENV->open: DB_RUNRECOVERY: Fatal error, run database recovery
    I thought the issues might be because I use encrypted database but the same things happen whether I use PRAGMA key="****************" in my scripts or not. I haven't played with DB_CONFIG - should I be creating a DB_CONFIG yet?
    I'm using Win 7 pro (x64), i5 processor with 8GB RAM, disks are a RAID10 array formatted as NTFS. Same errors occur if I try to create the database on a FAT32 USB key so it's probably not a filesystem problem. I used Visual Studio 10 and MSVCRT version 10 when building binaries myself. I notice the downloaded binaries were built against MVCRT version 8, so the problem doesn't look tied to the version of the VC runtime as it occurs on multiple versions.
    Can anybody help please? I would like to try BerkeleyDB but can't get past the first hurdle.
    Edited by: 856299 on 03-May-2011 10:46

    Hello,
    If you can provide a small stand-alone program to reproduce the problem along with the steps to reproduce it, I will give it a try.
    Thank you,
    Sandra

  • Primary key values

    hi
    i have created table like.
    create table sample(sid varchar2(10) primary key, sno number);
    inserted data like this
    sid sno
    AB10 10
    BA11 11
    AB12 11
    now i want to insert values into sid at frontend side..
    here my job here i want io insert values into sid(PK) from backend
    suppose ifs sid is number type
    i can insert values like select stmt..
    like
    select decode(max(sid), null,1,max(sid)+1) into variable from table_name;
    but here sid is varchar2 type
    so how to compare the value into database before value was inserted.???

    OraclePLSQL wrote:
    hi
    i have created table like.
    create table sample(sid varchar2(10) primary key, sno number);
    inserted data like this
    sid sno
    AB10 10
    BA11 11
    AB12 11
    now i want to insert values into sid at frontend side..
    here my job here i want io insert values into sid(PK) from backend
    suppose ifs sid is number type
    i can insert values like select stmt..
    like
    select decode(max(sid), null,1,max(sid)+1) into variable from table_name;
    but here sid is varchar2 type
    so how to compare the value into database before value was inserted.???
    Why you dont use a number as a data type of your PK

  • Populating primary key from My SQL

    I have a table called MEMBERS in MY SQL with BEFORE INSERT trigger on it to create the primary key. Trigger works when I use the MYSQL prompt to insert. By Using BC in 10.1.3 , I want to populate the primary key (memberid) when insert any record in to this table. In the model, 'primary key','& TRansient' are the only properties selected for the entity.
    When I insert using BC the record in not being created. How do I make it work.
    Following is the trigger on the table.
    CREATE OR REPLACE TRIGGER ASSIGN_MEM_ID
    BEFORE INSERT ON MEMBERS FOR EACH ROW
    BEGIN
    IF :NEW.MEMBERID IS NULL OR :NEW.MEMBERID < 0 THEN
    SELECT memid
    INTO :NEW.MEMBERID
    FROM MemberSequence;
    UPDATE MemberSequence
    SET memid= memid+1;
    END IF;
    END;
    Any help is appreciated.
    Thanks
    nk

    Try using the DBSequence data type for the column.
    see "6.6.3.8 Trigger-Assigned Primary Key Values from a Database Sequence" in the ADF Developer Guide.
    http://download.oracle.com/docs/html/B25947_01/bcentities006.htm#sm0147

  • Violation of PRIMARY KEY constraint . Cannot insert duplicate key in object

    hi i am using SQL Server, when i try to insert data from my jsp page it is inserting the data double time and when i try to submit for second time it is showing the following error.
    Violation of PRIMARY KEY constraint 'PK_EMPLOYEE'. Cannot insert duplicate key in object 'EMPLOYEE'.
    I didnt set identity for primary key. If i try to set identity to true then it is allowing data to submit only if i uncheck my primary key column in cached row set. And if i uncheck that primary key element then i can not retrieve the data by edit button. So how to solve this problem.
    Please any help would be appreciated.
    Thank You in Advance.

    Hi,
    I am providing support to one of our clients, where we have jobs scheduled to load the data from the tables in the source database to the destination database via SSIS packages. The first time load is a full load where we truncate all the tables in the destination
    and load them from the source tables. But from the next day, we perform the incremental load from source to destination, i.e., only modified records fetched using changed tracking concept will be loaded to the destination. After full load, if we run the incremental
    load, the job is failing with the error on one of the packages "Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object '<tablename>'. The duplicate key value is <1234>, even though there are no duplicate records. When we
    try debugging and running the failing package, it runs successfully. We are not able to figure out why the package fails and when we run the next day it runs successfully. Request you to help me in this regard.
    Thank you,
    Bala Murali Krishna Medipally.
    I suspect you are trying to insert modified records instead of updating.

  • Using a custom PL/SQL to populate the primary key in a tabular form

    I want to use a Custom PL/SQL Function to populate the primary key when I insert a new record into a tabular form. I want to get the value from a hidden page Item. The code I am using for the primary key source is:
    BEGIN
    INSERT INTO TEAM_MEMBERS(TEAM_ID)
    VALUES(:P75_TEAM_ID);
    END;
    When I try to insert a new record I get the following error:
    Error      ERR-1904 Unable to compute item default: type = Function Body computation_type= BEGIN INSERT INTO TEAM_MEMBERS(TEAM_ID) VALUES(:P75_TEAM_ID); END; .
    ORA-06550: line 5, column 2: PLS-00103: Encountered the symbol ";" when expecting one of the following: begin case declare end exception exit for goto if loop mod null pragma raise return select update while with << close current delete fetch lock insert open rollback savepoint set sql execute commit forall merge pipe The symbol "exit" was substit
    Any ideas what I am doing wrong?
    Thanks!

    Brian - Sometimes whitespace at the end of the block causes this. Be sure to trim everything after the last semicolon including tabs and newlines.
    Scott

  • Triggers to insert primary key

    I have two tables in database namely CM_BOM and CM_BOM_ITEM. The table columns are as follows :
    In CM_BOM table
    CR_ID
    CR_BOM_CODE
    CR_BOM_NAME
    CR_FG_CODE
    CR_ID is primary key
    Trigger to insert primary key data is as follows :
    CREATE OR REPLACE TRIGGER COSTMAN."CM_BOM_T1"
    BEFORE INSERT ON "CM_BOM"
    FOR EACH ROW
    DECLARE
    L_ID NUMBER;
    BEGIN
    IF :NEW.CR_ID IS NULL THEN
    :NEW.CR_ID := CM_RECIPE_SEQ.NEXTVAL; --L_ID;
    END IF;
    END;
    In CM_BOM_ITEM table
    CR_ID
    CR_ITEM_ID
    CR_FG_CODE
    CR_RM_CODE
    CR_RM_QTY
    CM_ITEM_ID is primary key. Trigger to insert primary key data is as follows :
    CREATE OR REPLACE TRIGGER COSTMAN."CM_BOM_ITEM_T1"
    BEFORE INSERT ON "CM_BOM_ITEM"
    FOR EACH ROW
    DECLARE
    L_ID NUMBER;
    BEGIN
    IF :NEW.CRI_ITEM_ID IS NULL THEN
    :NEW.CRI_ITEM_ID := CM_RECIPE_SEQ.NEXTVAL;
    END IF;
    END;
    Now, i want to the CR_ID in table CM_BOM_ITEM to get automatically inserted while adding any rows in the table.
    How could i do this ? Please suggest ?
    Yogesh

    In your code where you perform the insert into the parent table, you can use the RETURNING clause to receive the primary key value that the trigger on the parent table has assigned to the parent-row that was just inserted.
      insert into parent_table(....) values(....)
      returning CR_ID into some_local_variable;Then use this value when you insert the foreign key row subsequently.

Maybe you are looking for

  • Jtable: display sortable columns

    Hi all, As I undersatnd, by default jtable shows the sorting triangle only after you click on the column header. I wonder how you could display a disabled sorting triangle icon on sortable columns which becomes enabled after you click on the column h

  • When i start my mac all kinds of programs automatically open up but under my login items is nothing

    When i start my macbook pro  alot of startup programs appear on my home screen even though under my system preferences in login items there is nothing selected

  • How to identify which Hub is at 0x4b300000

    Most recent instances; 2/18/12 9:13:19 PM kernel USBF: 160.386 AppleUSBHubPort[0xb52b200]::FatalError - Port 4 of Hub at 0x4b300000 reported error 0xUSBF: e00002eb while doing 160.setting port power 2/18/12 9:13:35 PM kernel AppleUSBHubPort[0xb533500

  • Unable to mount removable device.

    Hi, Just plugged my Archos media player in.  The icon appeared on the xfce desktop, but I can't read it.  I get this error message, anyone know how to overcome it? Unable to mount "A604": Xlib: extension "Generic Event Extension" missing on display "

  • "startManagedWebLogic.cmd  ATGProduction" error

    Hi I have installed ATG Commerce Reference Store and have been getting this error while starting the ATGProduction server as per this step on the install guide http://docs.oracle.com/cd/E22630_01/CRS.1002/pdf/ATGCRSInstall.pdf Starting the Publishing