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

Similar Messages

  • What is the best way to do this? I am stuck!!

    I have a block with this, PLEASE help! I am writing a plsql package that is going to create a custom table everything is going fine EXCEPT that I don’t know what will be the best way to do this. Please point me in the right direction a function or something:
    I have three tables:
    My custom table SZSLIFE
    Two existing tables in my DATABASE:
    SGBSTDN,
    SLRRASG
    For this pidm (primary key). I have the following records in the SLRRASG table:
    SLRRASG_PIDM     SLRRASG_BLDG_CODE     SLRRASG_ROOM_NUMBER     SLRRASG_TERM_CODE     SLRRASG_RRCD_CODE     SLRRASG_BEGIN_DATE
    139203     ADD     103     200490     RCOM     09/02/2004
    139203     ADD     103     200510     RCOM     01/24/2005
    139203     BLA     001     200390     RCOM     09/03/2003
    139203     BLA     001     200410     RCOM     01/25/2004
    139203     HRK     101     200690     RCOM     08/31/2006
    139203     RIV     11     200590     RCOM     09/01/2005
    And I have the following records in the SGBSTDN table.
    SGBSTDN_PIDM     SGBSTDN_TERM_CODE_EFF     SGBSTDN_STST_CODE     SGBSTDN_LEVL_CODE     SGBSTDN_STYP_CODE     SGBSTDN_TERM_CODE_MATRIC
    139203     200390     AS     UG     C     200390
    139203     200410     AS     UG     C     200390
    139203     200590     DW     UG     C     200390
    139203     200610     IS     UG     C     200390
    139203     200660     AS     UG     C     200390
    139203     200690     AS     UG     E     200390
    139203     200710     IS     UG     C     200390
    So far I have been able to insert the following records in my custom table. This data is coming from the sgbstdn table
    SZSLIFE_PIDM     SZSLIFE_SLRRASG_TERM_CODE     SZSLIFE_STUDENT_STATUS_CODE     SZSLIFE_STUDENT_STATUS_DESC     SZSLIFE_STUDENT_TYPE_CODE     SZSLIFE_STUDENT_TYPE_DESC     SZSLIFE_STUDENT_LEVEL_CODE     SZSLIFE_STUDENT_LEVEL_DESC
    139203     200390     AS     Active     C     Continuing     UG     Undergraduate
    139203     200410     AS     Active     C     Continuing     UG     Undergraduate
    139203     200590     DW     Directed to Withdraw     C     Continuing     UG     Undergraduate
    139203     200610     IS     Inactive     C     Continuing     UG     Undergraduate
    139203     200660     AS     Active     C     Continuing     UG     Undergraduate
    139203     200690     AS     Active     E     Readmit/Re-entry     UG     Undergraduate
    139203     200710     IS     Inactive     C     Continuing     UG     Undergraduate
    NOW the question is: I need to insert the rows from the term 200490 and 200510 because there is data in the slrrasg table for those terms BUT the data that I need to insert is coming from the SGBSTDN table and there is not data for those terms in sgbstdn, so my user is telling my that it is okay to insert the previous term from sgbstdn for example: for the term 200490 I need to insert trhe 200490 in the szslife_slrrasg_term_code but I also need to insert the row from the 200390(previous one) from SGBSTDN.
    The same for 200510 insert 200510 in szslife_slrrasg_term_code but the rows from the term 200410 in SGBSTDN.
    Please give some ideas of how to do this. I will highly appreciate.

    Thank you very much for your answer, I have to confess that I am confused, never code this way. It looks very cool, I will like to learn this technique.
    This is what I have using my tables and my columns.
    What is the idea here? create a table 4 on the fly with all the coulmns that I need? This is what I have but I don't thing is going to work.
    2) do you need to have the same number of columns in the select like when you do a UNION?
    WITH tab1 AS
    (SELECT
    sgbstdn_term_code_eff,
    sgbstdn_term_code_eff,
    sgbstdn_stst_code,
    sgbstdn_styp_code,
    sgbstdn_levl_code,
    sgbstdn_resd_code
    FROM sgbstdn
    UNION ALL
    SELECT
    slrrasg_term_code,
    slrrasg_bldg_code ,
    slrrasg_room_number,
    slrrasg_rrcd_code ,
    slrrasg_begin_date ,
    slrrasg_end_date,
    slrrasg_ascd_code
    FROM SLRRASG
    UNION ALL
    SELECT
    szslife_slrrasg_term_code,
    szslife_student_status_code,
    szslife_student_type_code,
    szslife_student_level_code,
    szslife_student_level_desc,
    szslife_residency_code,
    szslife_building_code,
    szslife_room_number,
    szslife_assignment_begin_date,
    szslife_assignment_end_date,
    szslife_assignment_status
    FROM szslife
    UNION ALL
    SELECT NEW_TABLE ---QUESTION what I need to select here all the columns from table 1,2,3?
    tab2 AS
    (SELECT
    sgbstdn_term_code_eff,
    sgbstdn_term_code_eff,
    sgbstdn_stst_code,
    sgbstdn_styp_code,
    sgbstdn_levl_code,
    sgbstdn_resd_code
    FROM sgbstdn
    UNION ALL
    SELECT
    szslife_slrrasg_term_code,
    szslife_student_status_code,
    szslife_student_type_code,
    szslife_student_level_code,
    szslife_student_level_desc,
    szslife_residency_code,
    szslife_building_code,
    szslife_room_number,
    szslife_assignment_begin_date,
    szslife_assignment_end_date,
    szslife_assignment_status
    FROM szslife
    UNION ALL
    SELECT NVL(tab2.a,lag(tab1.a) over(ORDER BY tab1.a))
    FROM tab1, tab2
    WHERE tab1.a = tab2.a(+)
    I will apprecite your help, I did look in my books for a similar example but not luck.
    Rogelio

  • HT1451 I need to move my library from my old computer to my new laptop. What's the best way to do this?

    I need to move my library from my old computer to my new laptop (Windows 8). What's the best way to do this?

    These are two possible approaches that will normally work to move an existing library to a new computer.
    Method 1
    Backup the library with this User Tip.
    Deauthorize the old computer if you no longer want to access protected content on it.
    Restore the backup to your new computer using the same tool used to back it up.
    Keep your backup up-to-date in future.
    Method 2
    Connect the two computers to the same network. Share your <User's Music> folder from the old computer and copy the entire iTunes library folder into the <User's Music> folder on the new one. Again, deauthorize the old computer if no longer required.
    Both methods should give the new computer a working clone of the library that was on the old one. As far as iTunes is concerned this is still the "home" library for your devices so you shouldn't have any issues with iTunes wanting to erase and reload.
    I'd recommend method 1 since it establishes an ongoing backup for your library.
    If you have an iOS device that syncs with contact & calendar data on your computer you should migrate this information too. If that isn't possible create a dummy entry of each type in your new profile and iTunes should offer to merge the existing data from the device into the computer, otherwise the danger is that it will wipe the information from the device.
    If your media folder has been split out from the main iTunes folder you may need to do some preparatory work to make it easier to move. See make a split library portable.
    Should you be in the unfortunate position where you are no longer able to access your original library, or a backup of it, then see Recover your iTunes library from your iPod or iOS device for advice on how to set up your devices with a new library with the maximum preservation of data. If you don't have any Apple devices then see HT2519 - Downloading past purchases from the App Store, iBookstore, and iTunes Store.
    tt2

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

  • Best way to change partition key on existing table

    Hi,
    Using Oracle 11.20.3 on AIX.
    We have a table about 800 million rows and 120gb in size.
    Want to try copies oif this table to evalaute different partitiong strategies.
    What is the quickest way to do this?
    Would have liked say datapump table 1 tro disk and datapumo import the data to new table but do the tables need to be of the same format.
    Thanks

    >
    Using Oracle 11.20.3 on AIX.
    We have a table about 800 million rows and 120gb in size.
    Want to try copies oif this table to evalaute different partitiong strategies.
    What is the quickest way to do this?
    Would have liked say datapump table 1 tro disk and datapumo import the data to new table but do the tables need to be of the same format.
    >
    First your subject asks a different question that the text you posted: Best way to change partition key on existing table. The answer to that question is YOU CAN'T. All data has to be moved to change the partition key since each partition/subpartition is in its own segment. You either create a new table or use DBMS_REDEFINITION to redefine the table online.
    Why do you want to export all data to a file first? That just adds to the time and cost of doing the op.
    What problem are you trying to use partitioning to solve? Performance? Data maintenance? For performance the appropriate partitioning key and whether to use subpartitions depends on the types of queries and the query predicates you typically use as well as the columns that may be suitable for partition keys.
    For maintenance a common method is to partition on a date by year/month/day so you can more easily load new daily/weekly/monthly data into its own partition or drop old data that no longer needs to be kept online.
    You should use a small subset of the data when testing your partitionings strategies.
    Can you do the partitioning offline in an outage window? If not then using the DBMS_REDEFINITION is your only option.
    Without knowing what you are trying to accomplish only general advice can be given. You even mentioned that you might want to use a different set of columns than the curren table has.
    A standard heap table uses ONE segment for its data (ignoring possible LOB segments). A partitioned/subpartitioned table uses ONE segment for each partition/subpartition. This means that ALL data must be moved to partition the table (unless you are only creating one partition).
    This means that every partitioning scheme that uses a different partition key requires ALL data to be moved again for that test.
    Provide some information about what problem you are trying to solve.
    >
    Is this quicker than datapump?
    >
    Yes - exporting the data simplying moves it all an additional time. Ok to export if you need a backup before you start.
    >
    Found artcle which talks about using merge option on datapump import to convert partitioned table to non-partitioned table.
    >
    How would that apply to you? That isn't what you said you wanted to do.

  • URGENT - Items archiving in Portal - Whats the best way to do this ?

    Gurus,
    My client has following requirement -
    - The client has lots and lots of content.
    - The content must show on site for 6 months.
    - After 6 months, the content goes to archives (meaning - it does not show on site, but that does NOT mean its deleted - its kind of hidden)
    - The archive content must be searchable
    - After 4 years some content expires while some of it remains in archive forever
    Currently, the client stores the content on a file system and there is a process that moves the items after 6 months to an archiving area and after 4 years some content is deleted and some is retained forever.
    What is the best way to approach this requirement ?
    If there is a solution how to move their existing system (content valid for 6 months and archives for last 4 yrs) to portal ?
    Any help would be greatly appreciated.
    Thanx
    Hero

    There are a couple of ways to do this:
    1. If the items are all file items and don't have extended attributes, you can just use WebDAV to move the items to an archive location (can be another page or a file system). Use a WebDAV command line utility like sitecopy, combined with the WWSBR_ALL_ITEMS view to select the content. sitecopy should be able to select items based on their last modified date, so you may not have to use the view.
    2. If you also want to archive the attributes, or if the items include non-file items, you'll need to use the content management APIs to copy the items to an archive page. Currently there is no delete API, so once you've copied the items you'll have to expire the originals and then manually purge them.
    Regards,
    Jerry
    PortalPM

  • Narrating Keynote (Voice over slides)?  What is the best way to do this?

    If I have a keynote presentation and I need it narrated (like a a voice over) what is the best way to do this?
    Is it to record an audio file then insert it somehow into the presentation?
    Sorry if this is a dumb question, just not sure how to make it work. I need my boss to do the voice over- so I will probably only get one shot.

    This forum thread offers some options to do this. One simple strategy is to record separate bits of narration for each slide, and simply attach that to each slide. When the presentation is run, the audio file will play for each slide. This approach is much easier than alternatives, but the downside is that it does not allow for narration across slides, which may or may not be important to you. If it is necessary, then you should check out the option (discussed in the thread) of pre-recording the entire narration, then using Soundflower and Keynote's Record Slideshow functionality to create a show with narration.

  • Hi, I bought my iPhone in Canada but have moved to Australia. I need to speak with someone at Apple Canada what is the best way to do this? Is there is an e-mail address?

    Hi, I bought my iPhone in Canada but have moved to Australia. I need to speak with someone at Apple Canada what is the best way to do this? Is there is an e-mail address? When I call the Apple Canada number it says I can't call from my location.

    In what way did you buy your iPhone? If you paid full price at the Apple Store then your phone should be provider unlocked and should work with practically any SIM card you choose to insert in it. If you bought it cheaper with a contract then it's provider locked then your best bet is to call your cellular provider in Canada. Be sure to note your IMEI number (Settings > General > About) as they're going to need it to do an unlock. Be aware they may or may not charge for this.

  • HT4413 I want to transfer about three thousand photos on my MacAir to my iMac. Any suggestions on the best way of doing this?

    I want to transfer about three thousand photos on my MacAir to my iMac. Any suggestions on the best way of doing this?

    Are the photos in iPhoto?
    If they are, you can simply copy your iPhoto Library (located in your Pictures folder) to a thumb drive or external drive and then copy it over to your other Mac. This will only work if the iMac has the same version (or later version) of iPhoto as does the Macbook Air.  Then on the iMac, if you want to combine this new library with the existing one over there, use iPhoto Library Manager (a free download program).
    If you want to copy over only a portion of that iPhoto library, iPhoto Library Manager can create a smaller library containing just the photos you want to include. Then copy that smaller library.

  • My old computer is dying and I want to transfer my account to my new computer.  I will not be using the old computer at all.  What is the best way do do this?

    I want to stop using my old computer completely and transfer my itunes account to my new computer.  What is the best way to do this?

    A simple search

  • My Macbook pro was stolen 09/12, the police just returned it to me. I want to remove all the data and start over. Format the drive's etc. I have windows 7 on 1 partion and mountain lion OSX on the apple partition. How is the best way to do this?

    My Macbook pro was stolen 09/12, the police just returned it to me. I want to remove all the data and start over. Format the drive's etc. I have windows 7 on 1 partion and mountain lion OSX on the apple partition. How is the best way to do this?

    Have a look here...
    what-to-do-when-your-hard-drive-is-full.html

  • TS1314 I have lots of organized photos on my PC and I want to keep them organized to sync to ipad.... how is the best way to do this?

    I have spent a lot of time saving, organizing and arranging photos (for the last 7 years) on my PC, and would like to know the best way to transfer these, AND MAINTAIN THE ORGANIZATION OF THE FOLDERS, to my new ipad (and later, my iphone). I have a really good system, and I do not want to have to do it all over again, on the ipad. I DO NOT want to subscribe to another monthly service fee (i.e. the iCloud) but DO have iTunes on my PC.
    What is the simplest method to do this ?  I have tried synching, but, each time have lost photos (on my ipad) OR have had NO ORGANIZATION AT ALL to the photos once synced.  I have all these photos (5.6gb) in the My Pictures folder, then subdivided into years, then subdivided into events and months within the years.  So, my transfer of the My Picures folder, completely transfers all of them, but with NO further organization.  Again, I have spent years doing this, and don't want to have to re-invent the wheel. 
    Can someone advise (or even better, lead me to a youtube video) that accurately shows the best way to do this ?
    Thank you, in advance, for your help.
    p.s.  I particularly enjoy Dan Nations very informative articles on how to get the best from my products.  And, wish Apple would explain "how it works" regarding the syncing methods on the Operating System.  It is the only thing I "don't get" about using my iPad..... meanwhile I LOVE my new mini ! ! ! ! ! ! ! thanks Apple, for keeping things simple.... Please don't change that !

    Correct, it will only be one-level, the Photos app doesn't support sub-albums - the sub-folders photos will be included in the parent's album.
    If you select My Pictures at the top of the Photos tab when syncing, then you should get an album for each folder that is directly under it - so if I understand correctly what you described then that would mean an album for 2013, one for 2012 etc. And each of those should include all the photos in the subfolders under it - so 2013 would include the photos from the events and months subfolders under it.
    You can't sync them separately, only the contents of the last sync remains on the iPad, by not including a folder in the next photo sync you are effectively telling iTunes that you no longer want that folder/album on the iPad so it will be removed and be replaced by the contents of the new sync (you can't delete synced photos directly on the iPad, instead they are deleted by not including them in the next sync).
    The app that I use, Photo Manager Pro, allows you to select and copy a folder (via FTP), but you would need to select each subfolder individually, which if you have a lot would be time-consuming (I think that if you select '2013' it would ignore the folders beneath it).

  • I am trying to make a pdf of a file and I need to get the file size to be no bigger than 10MB. What is the best way to do this

    I am trying to make a pdf of a file and I need to get the file size to be no bigger than 10MB. Even when I save it, the image quality at minimum the file size is 10.9 MB. What is the best way to do this

    @Barbara – What purpose is that PDF for? Print? Web?
    If web purpose, you could convert CMYK images to sRGB. That would reduce the file size as well.
    A final resort to bring down file size is:
    1. Print to PostScript
    2. Distill to PDF
    That would bring file size down even more. About 20%, depending on the images and other contents you are using, compared with the Acrobat Pro method. If you like you could send me a personal message, so we could exchange mail addresses. I could test for you. Just provide the highres PDF without any downsampling and transparency intact. Best provide a PDF/X-4.
    I will place the PDF in InDesign, print to PostScript, distill to PDF.
    Uwe

  • I want to upgrade my Imac from tiger 10.4.11 to Mac OS 10.6 Snow Leopard. What is the best way to do this.

    I have just purchased an iphone 4 and it needs me to have the latest itunes on my computer.  I have not upgraded by computer for some time and thought this is probably the time to do it. My computer is an imac intel with Tiger 10.4.11. I want to upgrade my Imac from tiger 10.4.11 to Mac OS 10.6 Snow Leopard or higher.  What is the best way to do this?  Appreciate any help as I am out of practice. I used to be an old hand at this, but things have moved on since I didn't upgrade or use my computer as much!

    Catherina wrote:
    ...  What is the best way to do this?
    The best way, really the only way, is to purchase Snow Leopard.
    Online (UK): http://store.apple.com/uk/product/MC573/mac-os-x-106-snow-leopard
    Elsewhere: call the phone number in the Apple Online Store.
    Apple's price is $19.99, £14.00, €18.
    Snow Leopard is not available to download from any legitimate source.
    Once you install Snow Leopard, upgrade iTunes to version 10.7 or the latest, iTunes 11.
    iTunes 10.6.3 is the last version of iTunes to support Mac computers with Mac OS X 10.5.8 with either Intel or PowerPC processors, but since you have an Intel iMac, the best solution is to purchase Snow Leopard. Leopard is no longer available from Apple and prices from aftermarket vendors can be unreasonably high.

  • Urchased a new desktop pc and I want to move itunes and all files including IPAD apps to my new computer and delete off my old one.  What is the best way to do this?

    I just purchased a new desktop PC and want to move Itunes and all my Ipad Apps to new computer, and delete off my old computer.  What is the best way to do this?

    Hi,
    See Here for Transferring your iTunes Library
    http://support.apple.com/kb/HT4527
    Make sure Everything is working to your satisfaction Before Deleting anything from your old computer...
    Cheers,

Maybe you are looking for