Best way to do an Insert or Update

I am doing some insert/updates via php to oracle.
Each one will have to return an id to php.
If its an insert it will return the new id (generated by a trigger and sequence)
if its an update it will return the id.
Is the best way to do this with a seperate insert statement and update stament ?
Or a Merge for both ? I like merge but then how do you return the ID in the same statement...

Pleiadian wrote:
If the id is generated by a trigger, you will not have control over the sequence and would have to query the id after insert/update.
In this specific scenario where you want to return the id, it may be better not to use a trigger, but to explicitly call the sequence.nextval and store it in a variable so you can return it at the end of the function.
Why?  You can still use a trigger and return the value into a variable...
SQL> create table mytable (id number, myval varchar2(20))
  2  /
Table created.
SQL> create sequence mysequence
  2  /
Sequence created.
SQL> create or replace trigger trg_mytable
  2  before insert on mytable
  3  for each row
  4  begin
  5    select mysequence.nextval into :new.id from dual;
  6  end;
  7  /
Trigger created.
SQL> set serverout on
SQL> create or replace procedure insert_rec(val varchar2) is
  2    v_id number;
  3  begin
  4    insert into mytable (myval) values (val)
  5      returning id into v_id;
  6    dbms_output.put_line('Record inserted with id: '||v_id);
  7  end;
  8  /
Procedure created.
SQL> exec insert_rec('Test');
Record inserted with id: 1
PL/SQL procedure successfully completed.
SQL> exec insert_rec('Test2');
Record inserted with id: 2
PL/SQL procedure successfully completed.

Similar Messages

  • Best way to run about 200,000 update statements?

    Just throw them all in SSMS all at once? That doesn't seem like the best way especially since something may fail part way through. What would you suggest? Do it in code?

    Some samples:
    update XC01_CLME_MEMBER set CLME_LAST_NAME='BRAINARD' where RUN_DATE_KEY=287 and CLMS_CLCL_KEY=483584 and CLME_LAST_NAME = 'OFTEDAHL'
    update XC01_CLME_MEMBER set CLME_LAST_NAME='BRAINARD' where RUN_DATE_KEY=297 and CLMS_CLCL_KEY=796073 and CLME_LAST_NAME = 'OFTEDAHL'
    update XC01_CLME_MEMBER set CLME_LAST_NAME='BRAINARD' where RUN_DATE_KEY=297 and CLMS_CLCL_KEY=796074 and CLME_LAST_NAME = 'OFTEDAHL'
    update XC01_CLCL_CLAIM set MEME_CK=6652504 where RUN_DATE_KEY=461 and CLMS_CLCL_KEY=1645516 and MEME_CK = 6652503
    update XC01_CLCL_CLAIM set MEME_CK=6652504 where RUN_DATE_KEY=461 and CLMS_CLCL_KEY=1645517 and MEME_CK = 6652503
    update XC01_CLCL_CLAIM set MEME_CK=6652504 where RUN_DATE_KEY=461 and CLMS_CLCL_KEY=1645518 and MEME_CK = 6652503
    update XC01_CLCL_CLAIM set MEME_CK=6652502 where RUN_DATE_KEY=921 and CLMS_CLCL_KEY=2413143 and MEME_CK = 6652503
    update XC01_CLCL_CLAIM set MEME_CK=3334351 where RUN_DATE_KEY=297 and CLMS_CLCL_KEY=819206 and MEME_CK = 3334352

  • Best way to do this: Insert if exists, otherwise update

    Hi Everyone,
    I'm trying to write a PL/SQL procedure to check whether a row is in Table A. If the row exists, then update. I was using a
    SELECT Count(1) into countVariable FROM Table A where pri_key = data;
    but was recommended otherwise since a count() does a tablescan. Intead, I was suggested to use BEGIN / EXCEPTION WHEN NO_DATA_FOUND.
    You see, I'm not really an Oracle person, but to me using an exception for logic flow control is a no no. Is this the proper way of doing things?
    What about if I did something like:
    SELECT 1 into countVariable FROM Table A where pri_key = data;
    Not sure....
    Thanks!
    dfa_geko

    Assuming you're on 9i or later, you're better off using MERGE
    SCOTT @ nx102 Local> create table a( pk number primary key, val varchar2(10) );
    Table created.
    Elapsed: 00:00:00.36
    SCOTT @ nx102 Local> create table b( pk number primary key, val varchar2(10) );
    Table created.
    Elapsed: 00:00:00.48
    SCOTT @ nx102 Local> insert into a values( 1, 'abc' );
    1 row created.
    Elapsed: 00:00:00.00
    SCOTT @ nx102 Local> insert into a values( 2, 'def' );
    1 row created.
    Elapsed: 00:00:00.00
    SCOTT @ nx102 Local> insert into b values( 2, 'ghi' );
    1 row created.
    Elapsed: 00:00:00.01
    SCOTT @ nx102 Local> commit;
    Commit complete.
    Elapsed: 00:00:00.00
      1  MERGE INTO b USING a ON (a.pk = b.pk)
      2  WHEN MATCHED THEN UPDATE SET b.val = a.val
      3* WHEN NOT MATCHED THEN INSERT (pk, val) VALUES( a.pk, a.val )
    SCOTT @ nx102 Local> /
    2 rows merged.
    Elapsed: 00:00:00.11
    SCOTT @ nx102 Local> select * from a;
            PK VAL
             1 abc
             2 def
    Elapsed: 00:00:00.01
    SCOTT @ nx102 Local> select * from b;
            PK VAL
             2 def
             1 abc
    Elapsed: 00:00:00.00
    SCOTT @ nx102 Local> Justin

  • The best way to keep an Index.pdx updated

    Hello,
    I am creating some index's for my go-workers on a server for searching.
    The problem is, these are large amounts of PDF files and we keep adding to the folders daily. Is there an easy way to keep the index updated without having to keep rebuilding it?
    thanks!
    barbara

    Try scheduling index updates:
    http://kb.adobe.com/selfservice/viewContent.do?externalId=328763&sliceId=2

  • Best way to install an iOS software update?

    Is it less problematic to install an iOS update like it's a new device, then sync from a backup before the upgrade, to restore app data?

    It doesn't make sense to reinvent the wheel. I simply follow the on-screen instructions and I've never had a problem with my Macs or my iPad.

  • What is the best way to update Currency information in SRM?

    Dear Experts,
    there was additional information introduced in R/3, with respect to a certain currency (this currecy got a second abbreviation, whereas the first abbreviation was set as the primary ISO code).
    Can you please help me understand, what is the best way to get this additional information updated in SRM 7.0 (Classic)?
    - Do we replicate via the DNL_CUS_BASIS3 object?...and if yes, do we replicate from Development R/3 system to development SRM system and than transport it to SRM Quality and Production...or do we replicate level by level, i.e. from R/3 development to SRM development and than from R/3 Quality to SRM Quality and so on...
    OR
    - Do we update this change manually in SRM Development and than transport it to SRM Quality and Production?
    Thank you very much.

    Please elabotate what additional information regarding currency you need to update.
    As per std. SRM we may use "BBP_GET_CURRENCY" that will update currency details from ECC to SRM.
    But always you may add on required fields as required using enhancements.

  • What is the best way to get another object's method to update my GUI?

    package stuff;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class Test extends JFrame{
      private static JButton ProcessButton = new JButton();
      private static JLabel jLabel2 = new JLabel();
      public static void main( String args []){
         Test f = new Test();
         f.setSize(500,500);
         Container c = f.getContentPane();
         ProcessButton.addActionListener( new ActionListener(){
                                     public void actionPerformed(ActionEvent e) {
                                        jLabel2.setText("Connecting to DB");
                                        //Connection connection = Tools.setUpConnectionToDB(url,userName,pwd);
         c.add(ProcessButton, BorderLayout.NORTH);
         jLabel2.setText("My Label");
         c.add(jLabel2, BorderLayout.SOUTH);
         f.setVisible(true);
    {\code]
    The method setUpConnectionToDB can take 1 - 10 mins to complete. By this time a user will prob have quit my app thinking
    it's crashed because it doesn't update the GUI with a progress status. :(
    What is the best way to get this method to update the GUI of the app which calls it?
    Something like  Connection connection = Tools.setUpConnectionToDB(url,userName,pwd, this);
    ie this being a reference to the GUI's JFrame is what I'm trying to use?

    A handy class to know about but not really what I'm after.
    I need the method call
    Tools.setUpConnectionToDB(url,userName,pwd);
    to be able to update a component ( The JLabel ) on the GUI
    Connection connection = Tools.setUpConnectionToDB(url,userName,pwd, this);
    [\code]
    method defn:public static Connection setUpConnectionToDB( String url, String user, String pwd, JFrame f ){
    //Why doesn't this code below modify the GUI on the calling App?
    f.jLabel2.setText("Setting UP DB Connection");
    f.repaint();
    Connection c = null;
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    c = DriverManager.getConnection(url,user,pwd);
    catch(ClassNotFoundException e){
    JOptionPane.showMessageDialog(null , "Error loading DB driver");
    System.exit(0);
    catch(Exception e){
    JOptionPane.showMessageDialog(null , "Error connecting to DB, check config file");
    System.exit(0);
    return c;
    }[\code]

  • Best way to update individual rows of a Table?

    I've taken a look at some examples, though haven't gotten any clarification on this.  I am looking to have something close to a listbox or table to where I can update just a single column of row values at a 1 time per second pace.  I am looking to display our data-acquisition values in a table or listbox.  The single listbox seemed to work good for this, but I was unable to use row headers to list the channel names next to the channel values.  I was thinking about connecting the cursor values of two list-boxes to do this, but didn't find any info on this for the single list-box.
    I have a few questions:
    1) I have a 1D array to where I want to use that array of data to constantly update the first column (with a multitude of rows) of a table.  I am looking for the best route so as not to take up too much processing time in doing this.
    What is the best way to update individual rows of a table?   Invoke Node "Set Cell Value" ... or is there another method?
    2) Why is it that after every other iteration the row values are erased? 
    Also, for adding additional strings to the original arrray ... is it best to use the "Array Subset" and then the "Build Array" function, or the "Array Subset" and "Insert Into Array" function?
    See the attached example.
    Thanks.
    Solved!
    Go to Solution.
    Attachments:
    Table Example.vi ‏19 KB

    Jeff·Þ·Bohrer wrote:
    2) Why is it that after every other iteration the row values are erased?
    Classic race condition.  dump the for loop and p-node and just wire the 2D array to the table terminal.!
    I'm not seeing the race condition.  What I am seeing is the table emptying after the last element was written to it on every other run.  I saw watched this with highlight execution on.
    But I'm in full agreement with just writing to the terminal.  It is a 1D array, so you will need to use a build array and transpose 2D array in order for it to write properly.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • Best way to determine insertion order of items in cache for FIFO?

    I want to implement a FIFO queue. I plan on one producer placing unprocessed Orders into a cache. Then multiple consumers will each invoke an EntryProcessor which gets the oldest unprocessed order, sets it processed=true and returns it. What's the best way to determine the oldest object based on insertion order? Should I timestamp the objects with a trigger when they're added to the cache and then index by that value? Or is there a better way? maybe something coherence automatically saves when objects are inserted? Also, it's not critical that the processing order be precisely FIFO, close is good enough.
    Also, since the consumer won't know the key value for the object it will receive, how could the consumer call something like this so it doesn't violate Constraints on Re-entrant Calls? http://wiki.tangosol.com/display/COH34UG/Constraints+on+Re-entrant+Calls
    Thanks,
    Andrew

    Ok, I think I can see where you are coming from now...
    By using a queue for each for each FIX session then you will be experiencing some latency as data is pushed around inside the cluster between the 'owning node' for the order and the location of the queue; but if this is acceptable then great. The number of hops within the cluster and hence the latency will depend on where and how you detect changes to your orders. The advantage of assiging specific orders to each queue is that this will not change should the cluster rebalance; however you should consider what happens if the node controlling a specific FIX session is lost - do you recover from FIX log? If so where is that log kept? Remember to consider what happens if your cluster splits, such that the node with the FIX session is still alive, but is separated from the rest of the cluster. In examining these failure cases you may decide that it is easier to use Coherence's in-built partitioning to assign orders to sessions father than an attribute of order object.
    snidely_whiplash wrote:
    Only changes to orders which result in a new order or replace needing to be sent cause an action by the FIX session. There are several different mechanisms you could use to detect changes to your orders and hence decide if they need to be enqueued:
    1. Use a post trigger that is fired on order insert/update and performs the filtering of changes and if necessary adds the item to the FIX queue
    2. Use a cache store that does the same as (1)
    3. Use an entry processor to perform updates to the order object (as I believe you previously mentioned) and performs logic in (1)
    4. Use a CQC on the order cache
    5. A map listener on the order cache
    The big difference between 1-3 and 4, 5 is that the CQC is i) a SPOF ii) not likely located in the same place as your order object or the queue (assuming that queue is in fact an object in another cache), iii) asynchronously fired hence introducing latency. Also note that the CQC will store your order objects locally whereas a map listener will not.
    (1) and (3) will give you access to both old and new values should that be necessary for your filtering logic.
    Note you must be careful not to make any re-entrant calls with any of 1-3. That means if you are adding something to a FIX queue object in another cache (say using an entry processor) then it should be on a different cache service.
    snidely_whiplash wrote:
    If I move to a CacheStore based setup instead of the CQC based one then any change to an order, including changes made when executions or rejects return on the FIX session will result in the store() method being called which means it will be called unnecessarily a lot. It would be nice if I could specify the CacheStore only store() certain types of changes, ie. those that would result in sending a FIX message. Anything like that possible?There is negligible overhead in Coherence calling your store() method; assuming that your code can decide if anything FIX-related needs to be done based only on the new value of the order object then this should be very fast indeed.
    snidely_whiplash wrote:
    What's a partitioned "token cache"?This is a technique I have used in the past for running services. You create a new partitioned cache into which you place 'tokens' representing a user-defined service that needs to be run. The insertion/deletion of a token in the backing map fires a backing map listener to start/stop a service +(not there are 2 causes of insert/delete in a backing map - i) a user ii) cluster repartitioning)+. In this case that service might be a fix session. If you need to designate a specific member on which a service needs to run then you could add the member id to the token object; however you must be careful that unless you write your own partitioning strategy the token will likely not live on the same cache member as the token indicates; in which case you would want a ful map listener or CQC to listen for tokens rather than a backing map listener
    I hope that's useful rather than confusing!
    Paul

  • Best way to update custom table

    Hello experts,
    Iu2019m writing a report program and after pulling data from a custom table Iu2019m modifying certain fields within internal table and then eventually update custom table. The way Iu2019m updating custom table is working fine. However Iu2019m concern about performance issues because Iu2019m doing update on custom table within loop.
    Here is my code for reference.
    *&      Form  update_contracts
          text
    -->  p1        text
    <--  p2        text
    FORM update_contracts .
    Update record in an internal table first
      loop at izsc_compliance into wa_zsc_compliance..
        wa_zsc_compliance-zapproval = c_accepted.
        wa_zsc_compliance-CHANGED_DT = sy-datum.
        wa_zsc_compliance-CHANGED_TM = sy-uzeit.
        wa_zsc_compliance-CHANGED_BY = sy-uname.
        modify izsc_compliance from wa_zsc_compliance index sy-tabix.
        write:/ sy-tabix, wa_zsc_compliance-vbeln_new, wa_zsc_compliance-zapproval.
        if p_test is initial.
          move wa_zsc_compliance to zsc_compliance.
          update zsc_compliance.
        endif..
      endloop.
    Write records to database
      if p_test = 'X'.
        skip.
        write:/ 'Test mode'.
      endif.
    ENDFORM.                    " update_contracts
    Iu2019m not certain if there is any better way by not doing update within loop and update custom table outside this loop.
    Many thanks in advance.

    Hi,
    Yes, there is a better way to update the custom table. That will be more performance oriented and will be a much cleaner approach. As, I am not much aware of the custom table structure which you have in your program, the best way that I can suggest is to remove the update statement from that check. I guess you are checking against the mode - test or production. Once you have done the check, put the selected entries in an internal table which is same as database table. And then in a single command - a single array operation as it is commonly called, you can update the custom table.
    Have a look at the following link
    [Overwriting Several Lines Using an Internal Table|http://help.sap.com/saphelp_bw33/helpdata/en/fc/eb3a94358411d1829f0000e829fbfe/content.htm]
    [Inserting or Changing Lines|http://help.sap.com/saphelp_bw33/helpdata/en/fc/eb3ac8358411d1829f0000e829fbfe/content.htm]
    You can also scan the forum for multiple links and references and sample examples.
    Hope this will help. The above approach will be much more performance oriented and will help to optimize. Also, check where exactly you are providing the locking feature if at applicable in your business functionality.
    Regards,
    Samantak.

  • Best way to update an OLTP table ?

    Hi,
    We have an OLTP table with huge data.
    We need to update a status column from 'N' to 'Y' for almost 70% of rows based on some condition.
    This table may be accessed by hundreds of sessions at a time.
    So, what is the best way to do the same.
    Rgds,
    Rup

    if someone is using the table, ddl cannot be done (or at least you would have to wait maybe a long time)
    quick test...
    SQL> create table bank
      2  (id number primary key
      3  ,acc number
      4  ,ind varchar2(1)
      5  )
      6  /
    Table created.
    SQL> insert into bank
      2  select rownum
      3       , rownum * 10
      4       , 'N'
      5    from all_objects
      6   where rownum <= 10
      7  /
    10 rows created.
    SQL> commit;
    Commit complete.
    SQL> update bank
      2     set acc = -10
      3   where id = 10
      4  /
    1 row updated.new session
    SQL> alter table bank
      2  add new_ind varchar2(1)
      3  /
    alter table bank
    ERROR at line 1:
    ORA-00054: resource busy and acquire with NOWAIT specifiedwell, not a long time... but anyway you can't do ddl while someone is working on the table.

  • Best way to edit/update data in JSP ?

    Hi Friends,
    I want to know about Update / Edit data procedure in JSP.
    ie.
    If we have one form having 10 fields, and we need to change only
    1 field then do we require to set update query for all 10 fields ?
    don't it make some overload ?
    Can you give me solution like that ?
    and I want to update data like we use CakePHP scaffold functionality.
    data from database is displayed in field and we just need to edit data
    and save it.
    Can we have such in JSP ? see I don't know struts or any frameworks
    Better you will suggest way to do in JSP.
    for Insert I use Bean [ one java class get the parameters for all fields and query ]
    Please suggest me to set the value to field on edit / update
    and best way to update the data.
    -GkR

    It's easy if you want upade game files, not game engine binary.
    You can make your app that will load swf file. So you can make engine that will load all files externaly from device. Firstly you run app and if it connected by wifi - ask user for upadate wish and that simply download from http files as binary and save they using FileSystem

  • Whats the best way to check table before form deletion or update ?

    Hi, I have a func_staff table made up of a composite key - func_no and staff_id. I have a form where the datablock references this table.
    I need to be able to check that before a func_no and staff_id combination on the form are written to the database that that combination does not already exist in the table.
    What would be the code for that ? I've tried stuff like IF EXIST statements and even a select statement but I totally worded it it wrongly.
    To DELETE an entry in that same table, would the best way to be create an LOV for both func_no and staff_id, the problem with that would be if a user selected a combination that does not exist ? Could I create a combined LOV that would populate each field ?? (this way I could be 100% sure that the selected combination is valid)
    Thanks Peeps.

    hi,
    you can try and use the count(*), before deleting and updating
    lets say
    select count(*)
    into l_count
    from table_name
    where column1 = :block.column1
    and column2 = :block.column2;
    if l_count <> 1
    then
    insert into..........
    else
    show error message;
    raise form trigger failure;
    end if;
    similarly u can use l_count before deleting.
    regards,
    Mayank

  • Needs suggestion the best way database insertion using OSB

    Hi all, again and again I need your suggestion. Which is the best way for writing data to database using OSB in few tables as fastest as possible (speed consideration)?, should I make lots DB schema for supporting JCA adapter and transform each message and writing to database? OR should I call java callout then using EJB for writing to database?.

    Hi,
    We had the similar scenario in our project and this is my take on this.
    Its better to use a JCA DBAdapter to execute/invoke a stored procedure and then have the PL/SQL script for insertion into the Stored Procedure.
    As the OSB DBAdapter configuration is very tightly coupled to the DB structure any changes to the column types of the table will mean a regeneration of the adapter WSDL.
    In general even for other DB operations like select, delete, update... its is a good idea to use the stored procedure in conjunction with the DBAdapter to decouple the link to DB to some extent.
    Thanks,
    Patrick

  • 2.1 Out and Best way to Update if you are a mobile me subscriber's

    From My experience put your phone in to DFU mode and reset your phone back to new.
    Remember this works for me and I recommend it if you use MOBILE ME.
    Download the new Firmware and then follow the below
    http://www.ifonenation.com/2008/07/24/how-to-put-your-iphone-into-dfu-mode/
    once Itunes has installed the new firmware.
    Then re-sync your data again, as if you just bought it.
    If you use mobile me this is the best option for you as all your data is stored on apple servers and will update your phone from your mobile me account.
    ** you will loose the following... SMS and all call logs and your favorites some and all preference settings..
    To eliminate any confilicts from apps etc this is the best way to go and give your iphone a fresh start.
    I have always done this with the last updates and never had a problem with any conflicts, and performance issues.
    Remember this is for mobile Me users as all you Contacts,Callender, and Mail is stored remotly.
    Keep us posted on your 2.1 findings.
    I have full 3g NOW! yay

    The fastest way is to directly change the values in the catalog.pse9db database.  The database is a SQL Lite database, so if you know (or know someone who knows) how to run SQL queries against a database, you're in luck because Adobe did an excellent job of designing a highly normalized database schema.
    I highly recommend first trying this on a copy of your database.  In general, the procedure goes like this:
    Add one of your images on the P: drive into the catalog.  This will establish a listing for the P: drive and its identification in the volume_table table.
    Run a SQL query against the volume_table table to see a listing of all the rows.
    Note the values of the "id" column for your "thehive" volume and the "P:" volume.
    Run a SQL query against the media_table table to update the value of the volume_id column, replacing all instances of the "thehive" id number with the id number of your "P:" drive. The SQL query will look something like this:
    Update media_table
        set volume_id = "<your new value>"
            where volume_id = "<your old value>"
    I've tested this with PSE9.0.3 on Win7, changing the location from a CD on my E: drive to a USB stick on my F: drive.
    Good Luck!
    Ken

Maybe you are looking for

  • SOAP-- XI-- R/3

    Hello, I am working on a scenario which includes SOAP and IDOC. sri Message was edited by:         sri rao

  • HasPermission and UME Web Service Access

    Hi! Does anyone know how to call hasPermission from a web service? I have a web service running out on the WebAS, and I am trying to use an IUser from the Role Factory to call hasPermission(...); however it always returns false. Is it because there i

  • OData Refresh from On-Premise Datasource

    Hi In Office365 PowerBI Admin centre I have built a connection to our on-premise data warehouse, i.e. installed a gateway, created the connection, enabled cloud access and OData feed and added some views. My colleague has built an PowerView spreadshe

  • Should I uninstall Elements 11 after installing Elements 12?

    Should I uninstall Elements 11 after installing Elements 12?

  • Lumia 810 Direct PC sync with Outlook?

    How can I directly sync Outlook to my Lumia 810 for my contacts and calendar?  Is there an app that I can install?  Is there one in development? If there is I will patiently wait.  I am very huge on security and honestly I don't need my calendar and