How good my trigger & Create Sequence are written review my excerpt from PL/SQL

I have a CustomerHistory table.

Here's a sequence I created for the table:
CREATE SEQUENCE customerhistory_id_seq
START WITH 90
INCREMENT BY 10
MAXVALUE 90000
NOCYCLE
NOCACHE;
I created a trigger example the primary key of the history table:

CREATE OR REPLACE TRIGGER cushistory_bef_insert
BEFORE INSERT ON CustomerHistory
FOR EACH ROW
BEGIN
      SELECT customerhistory_id_seq.NEXTVAL INTO :NEW.CustomerHistoryID
      FROM DUAL;
END;
/
After each update, or delete, insert the old record in the history table:
CREATE OR REPLACE TRIGGER cushistory_aft_upddel
AFTER UPDATE OR DELETE ON CUSTOMER
FOR EACH ROW
BEGIN
      IF UPDATING THEN
            INSERT INTO CustomerHistory
                     *
            (
                 SELECT
                         :OLD.c.customerID,
                         :OLD.c.firstname,
                       :OLD.c.lastname,
                       :OLD.c.email,
                         .
                         .
                         .
                         :OLD.mr.roomtype,
                         .
                         .
                         .
                         :OLD.b.checkout,
                         'UPDATE',
                         SYSDATE
               FROM Customer c JOIN CustomerFamilyMember cf ON c.customerID = cf.customerID
                     JOIN Phone p ON c.customerID = p.customerID
                     JOIN ThirdParty t ON c.thirdpartyid = t.thirdpartyID
                     JOIN BookedRoom b ON c.customerID = b.CustomerID
                     JOIN MotelRoom mr ON b.roomID = mr.roomID
                     JOIN Motel m ON mr.motelID = m.motelID
          );
     
      ELSIF DELETING THEN
      
            INSERT INTO CustomerHistory
                     *
            (
                 SELECT
                         :OLD.c.customerID,
                         :OLD.c.firstname,
                       :OLD.c.lastname,
                       :OLD.c.email,
                         .
                         .
                         .
                         :OLD.mr.roomtype,
                         .
                         .
                         .
                         :OLD.b.checkout,
                         'DELETE',
                         SYSDATE
               FROM Customer c JOIN CustomerFamilyMember cf ON c.customerID = cf.customerID
                     JOIN Phone p ON c.customerID = p.customerID
                     JOIN ThirdParty t ON c.thirdpartyid = t.thirdpartyID
                     JOIN BookedRoom b ON c.customerID = b.CustomerID
                     JOIN MotelRoom mr ON b.roomID = mr.roomID
                     JOIN Motel m ON mr.motelID = m.motelID
          );
     
      END IF;
END;
/
1 are structured correctly 3 pl/sql code snippets?
2. in the last example, which is an alternative using the JOIN? If know join 5 tables is not a good
long term solution. Any idea?

Hello

Here are the bugs I find in your code.
Please view the description of test table and features for more information.

1 cushistory_aft_upddel is a level trigger line on client.
Querying the table inside the trigger would give the error table mutation.

ERROR at line 1:
ORA-04091: table XXXXX.CUSTOMER is mutating, trigger/function may not see it
ORA-06512: at "XXXXX.TEST_TRG", line 2
ORA-04088: error during execution of trigger 'XXXXX.TEST_TRG'

The only way you can acccess them using: old.col_name and: new.col_name.

2 table the customer is the only updated and so the new and the old mke sense only for the customer table. the old.b.col_name and old. XXX.col_name for all other tables mean nothing and will result in error;

Here is an excerpt of small test with tahe customer table and another table called check_in. You can extend the same thing for your problem.

sql> create table customer(
  2    cust_id number,
  3    cust_name varchar2(20));

Table created.

sql> create table check_in(
  2    cust_id number,
  3    check_in date,
  4    check_out date
  5  );

Table created.

sql> create table cust_history(
  2    cust_id number,
  3    cust_name varchar2(20),
  4    check_in  date,
  5    check_out date);

sql> insert into customer values (100, 'Rajesh');

1 row created.

sql> insert into customer values (200, 'kumar');

1 row created.

sql> insert into check_in values (100, sysdate-2, null);

1 row created.

sql> insert into check_in values (200, sysdate-3, null);

1 row created.

sql> commit;

Commit complete.

 create or replace trigger test_trg
 after update on customer for each row
 begin
   insert into cust_history
   select :old.cust_id,
          :old.cust_name,
          ci.check_in,
          ci.check_out
     from check_in ci
     where ci.cust_id = :old.cust_id;
 end;
 /

sql> select * from customer;

   CUST_ID CUST_NAME
---------- --------------------
       100 Rajesh
       200 kumar

sql> select * from check_in;

   CUST_ID CHECK_IN  CHECK_OUT
---------- --------- ---------
       100 25-DEC-09
       200 24-DEC-09

sql> select * from cust_history;

no rows selected

sql> update customer set cust_name = 'Rajesh2' where cust_id = 100;

1 row updated.

sql> commit;

Commit complete.

sql> select * from customer;

   CUST_ID CUST_NAME
---------- --------------------
       100 Rajesh2
       200 kumar

sql> select * from cust_history;

   CUST_ID CUST_NAME            CHECK_IN  CHECK_OUT
---------- -------------------- --------- ---------
       100 Rajesh               25-DEC-09

You can use the other tables to select as I used the check_in above. You don't need to access the customer table that you have values in the: old. and: new. variables for them.

Thank you
Rajesh.

Published by: Rajesh Chamarthi on December 26, 2009 21:30 added example.

Tags: Database

Similar Questions

  • How to allow a user to download a custom report generated from pl/sql?

    Hello

    I am putting together my first app APEX (v 3.1.2.00.02) and I have a requirement that I am not completely sure that the implementation.

    Basically, I have a page where the user can select a set of buildings that they validate. Buildings have an x, ordered as SDO_GEOMETRY and a few other attributes. For now, they select from a dropdown list and I run a SQL query that performs validation and I present the results in a table of Standard report. That everything is perfect.
    Now, there is a requirement to the release of the results of the report in another text running format (called a consultation file), with another desktop application can consume to direct the user to the buildings that need to be corrected. I've included an example of this output below.
    I so want to see the existing Standard report table and also have a link to download the file in. I can use a stored procedure to write output to the file of consultation, but I don't know how it is available for download.
    I could use UTL_FILE to write the browse file to a location on the server, but then I don't know what to do next.

    I'll have a look at the download section of file of the [the server HTTP mod_plsql User Guide | http://download.oracle.com/docs/cd/B19306_01/server.102/b14337/concept.htm#i1005866] but before we get too deep into it, I wanted to check if anyone has any better ideas how this implementation.

    Any help would be appreciated,
    Reggie


    The format of file browse will be as follows:
    BROWSE VERSION 1.0
    
    ELEMENT
      TAG "INPUT PARAMETERS"
      COMMENT "REVIEW operation executed on SAMPLE_BUILDINGS"
      COMMENT "4 elements logged from SAMPLE_BUILDINGS"
    
    ELEMENT
      TAG "ERROR"
      COMMENT "Building Point Outside Polygon"
      LOCATION 674444.431 696112.632
    
    ELEMENT
      TAG "ERROR"
      COMMENT "Building Point Overlaps Road"
      LOCATION 675419.950 697391.195
    
    ELEMENT
      TAG "ERROR"
      COMMENT "Duplicate Building Point"
      LOCATION 674205.041 697364.946
    
    ELEMENT
      TAG "ERROR"
      COMMENT "Building Point with no Address"
      LOCATION 675215.807 697178.701
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                

    You can use a procedure like this to allow a download of your file stored as a bfile type (in a directory):

       PROCEDURE download_bfile (
          file_in        IN   VARCHAR2 DEFAULT 'test.txt',
          directory_in   IN   VARCHAR2 DEFAULT 'DATA_PUMP'
       )
       AS
          lob_loc    BFILE;
          v_mime     VARCHAR2 (48) DEFAULT 'application/txt';
          v_length   NUMBER;
       BEGIN
          lob_loc := BFILENAME (directory_in, file_in);
          v_length := DBMS_LOB.getlength (lob_loc);
    
          OWA_UTIL.mime_header (NVL (v_mime, 'application/octet'), FALSE);
    
          HTP.p ('Content-length: ' || v_length);
    
          HTP.p (   'Content-Disposition:  attachment; filename="'
                 || SUBSTR (file_in, INSTR (file_in, '/') + 1)
                 || '"'
                );
    
          OWA_UTIL.http_header_close;
    
          WPG_DOCLOAD.download_file (lob_loc);
       END download_bfile;
    

    To perform this procedure of work of the Summit, you can use approach similar to the following:

    http://Apex.Oracle.com/pls/OTN/f?p=31517:15

    You can also have a look at this thread:

    Re: Need help with the analysis of a Blob in a Table

    It will give you lots of ideas how this problem could be solved.

    Denes Kubicek
    -------------------------------------------------------------------
    http://deneskubicek.blogspot.com/
    http://www.Opal-consulting.de/training
    http://Apex.Oracle.com/pls/OTN/f?p=31517:1
    -------------------------------------------------------------------

  • How to create the home group and how to connect two computers that are running windows 7. and also Remote Desktop connection!

    Someone help me how to create the home group and how to connect two computers that are running windows 7. and also Remote Desktop connection!
    step by step information!

    Hello

    I suggest you to refer to the links and check if it helps:

    Create a homegroup

    http://Windows.Microsoft.com/en-us/Windows7/create-a-HomeGroup

    Join a homegroup

    http://Windows.Microsoft.com/en-us/Windows7/join-a-HomeGroup

    Setting up a network home

    http://Windows.Microsoft.com/en-us/Windows7/setting-up-a-home-network

    Remote Desktop connection

    http://Windows.Microsoft.com/en-us/Windows7/products/features/Remote-Desktop-connection

    What types of connections remote desktop should I allow?

    http://Windows.Microsoft.com/en-us/Windows7/what-types-of-Remote-Desktop-connections-should-I-allow

    Remote Desktop connection: frequently asked questions

    http://Windows.Microsoft.com/en-us/Windows7/Remote-Desktop-connection-frequently-asked-questions

    Let us know if it helps.

  • Is it possible to change sequence settings after you start a project? Also, how can I know what sequence of parameters are best for clips that I have?

    Is it possible to change sequence settings after you start a project? Also, how can I know what sequence of parameters are best for clips that I have?
    The clips I have are HD and .mp3. MTS files.

    In the latest version of Premiere Pro, it is possible to change the settings for the sequence.

    You know what settings are best knowing what you are doing.  (Personally I'm fan of formal education for this.)  I know that sounds sarcastic, but, there is no right answer to the question whose parameters are the best.  There are many variables here, then... you really need to know what you're doing.

  • How is possible to create a smart collection to find all the photos that are not belongs to any collection?

    Hello

    How is possible to create a Smart Collection to find all the photos are not belongs to any collection?

    "Yesterday I was importing a lot of photo when my camera battery died then I succeeded him and continued to import without thinking that the previous import collection literally means" previous import. "

    So I need to find a way to create a smart collection that will reveal all the photos that do not belong to any collection.

    I solved the problem with a workaround is creating a collection based on the date of the photo which worked well, but must be nice to have a more general collection to find all the photo that are not from the collections.

    Thanks in advance,

    Marco.

    Another way to do

    1. Select all photos in the catalog

    2 dismiss a color label

    3. go to collections and multi select all your collections (ctrl)

    4. select images and give them a color

    5. return to the catalogue

    6. filter by color label - No

  • If the applications are written in Javascript, how can a developer protect the rights?

    I read that Firefox OS applications are written in Javascript, Html, and CSS. Can anyone see or copy the code? Is it possible to prevent it?

    BONES of Firefox applications are written in JavaScript. It does not support Java or Flash. Your code is automatically protected by copyright in some countries as the France, see the laws of your country. But if you want to hide your code, it is not possible. You can just make it unreadable with a mibified version.

  • How to distribute answers quiz sequence vertically on the slide?

    How to distribute answers quiz sequence vertically on the slide?  Of response boxes are all locked together, moving one of them moves all, but I would like to separate them and spread them out from each other.

    It has been possible in previous versions, but for some reason, they changed the model of slides, layout, put two answers in a non resizable box in the response box (which can be resized). And spacing didn't affect the lines of text within a single answer, oddly on the spacing between the answers. I tried all sorts of workarounds without a good result. I'm really sorry.

  • Track label/colors in my sequences are darker than usual.

    The labels/colours of the tracks in my sequences are super dark now compared to how they were before. I have not changed anything other than the update. Is it possible for me to solve this problem?

    Dark colors slowly steal my soul. In addition, it makes it difficult to see the track splits and transitions.

    It was an intentional change in 7.2.2 based on comments from some customers that the colors of the clip are too bright in the timeline panel. Since this change, we have received comments from a number of unhappy customers how we implemented the change. In the light of this entry, we have other options.

    In case you weren't aware, you can adjust the colors of label through the tab label good colors its name from the Preferences dialog box. But please note that due to the change of 7.2.2 colors will be darkened by 40% from the values that you set.

    Here are three other threads on this topic:

  • How triggers can be created in the table?

    Hi all
    How triggers can be created in the table?
    is 12 or as far as we can?

    There is no technical limit to the number of triggers you set (or, at least, not one that any rational person has never touched). He usually would not make sense to have more than one trigger of a given type on a particular table, even if you can come up with situations where you can have multiple triggers of the same type on a single table.

    Normally, when people ask this question, it is because someone (foolishly) he asked in an interview. Frequently, the interviewer is trying to determine if you know how many types of triggers there is no if you know if there are some esoteric limit on the number of triggers.

    Justin

  • When I turn my library of music in format mp3. I have duplicates.how can I know which songs are mp3

    I have a mp3 player.i sansa player - tunes doesn't recognize Sansa, so I need to transfer my music in windows media player. to do this I need to convert all my music in mp3 format.when I do that, then I can burn all my music and import to wmp.question is that when I convert to format mp3, how will I know which songs are mp3?

    You can create a smart playlist which, for example, collecting files converted based on the date that they are added to the library. It depends on how you want to proceed. If you want to permanently convert, I have a script called ConvertFormat which range the originals after conversion. Alternatively, you can temporarily change your media to the converted files folder are stored in a folder of new media, then once the process is complete you may add these files to your WMP library, reset the media in iTunes folder and delete the new additions to iTunes library, thus separating the two libraries.

    TT2

  • How good/bad is Reg Zooka?

    How good/bad is Reg Zooka and other registry cleaners? Do I still need to do anything in the registry? I read mixed reviews.

    There is NO SUCH THING as a 'good' registry cleaner - they are ALL, without exception, snake oil and dangerous.

  • How can I cancel my sequence when DI signal changed?

    Hello, I have a problem I want to stop my DI signal sequence has changed.

    How can I cancel my sequence when DI signal changed?

    Thank you

    Good idea

    Thank you

  • Microsoft PAINT - how can I amplify a drawing are in paint, enlarge the concentration of pixels?

    Microsoft PAINT - how can I amplify a drawing are in paint, to increase the concentration of pixels?

    Hi Uuj112,

    Concentration of the pixel depends on the quality of the image. If the image quality is very good, then you might be able to enlarge the picture with good quality.

    You can try to resize the pixels in Microsoft paint. Try the following steps.

    1. open Microsoft paint.

    2. click on the Home tab > resize

    3. click on Pixels and trying to adjust the horizontal size of the image.

    Bindu S - Microsoft Support
    Visit our Microsoft answers feedback Forum and let us know what you think

  • How to run a 32-bit program written in foxpro for windows (fpw26) under a window of 64 bit 7 or 8

    Original title: compatibility issue

    How to run a 32-bit program written in foxpro for windows (fpw26) under a window of 64 bit 7 or 8

    Thanks in advance

    32-bit programs work fine on 64 bit versions of Windows.  In fact, over 95% of the software that comes with the 64-bit Windows version is 32-bit, because there is no reason for re - programming software for upper bits when it would not net any performance gain.  Even Microsoft Office is 32-bit on a 64-bit computer.

    So to use a 32-bit program, just run it normally.  If there are failures, let us know what said failure.

    PS. the program may have other failures that are unrelated to the number of bits of the processor.  Try right click on the program and choose to resolve compatibility issues to try to fix it automatically.

  • insufficient privileges when you create sequence using the procedure

    CREATE OR REPLACE PROCEDURE schema1.proc1 AS
    BEGIN
    EXECUTE IMMEDIATE 'DROP SEQUENCE schema1.add_ins_seq';
    EXECUTE IMMEDIATE 'CREATE SEQUENCE schema1.add_ins_seq MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 1000 NOORDER  NOCYCLE';
    END;
    

    This procedure is created to schema1 by schema1.

    Schema1 boasts a CREATE SEQUENCE privilege.

    When I run this procedure through SQL Developer after the Cup to schema1, the error is thrown in insufficient privilege to CREATE SEQUENCE, however, DROP SEQUENCE is executed. I can create the sequence without the procedure call.

    If I add AUTHID CURRENT_USER so I don't get the error of insufficient privileges.

    Why it gives this error when the owner and the applicant of the procedure is schema1?

    Hello

    1st thing to know: when a procedure is defined (and updated), any privileges granted through ROLE is not taken into account. This is because these privileges can be active or not at the level of the session (as happens if for example a user has active 'role A' in session 1 but not in session 2 and if this role has been used to define a procedure?) The proecedure must at the same time be VALID in session 1 and INVALID session 2? Is not possible.

    Thus, for instance in a situation of 'standard': user SYSTEM has 'DBA Rôle', so you can for example make a sqlplus session "SELECT * v $ instance;", but you would write a procedure owned by system making instance_name SELECT INTO l_variable OF v$ instance;  "then"surprise": the procedure cannot be compiled because of the ORA-904 Table or view does not exist..." To be able to create the procedure, a DSS system needs to be done.

    2nd thing for your special case, a little more complex: default for a procedure is 'AUTHID DEFINE', but once more: it means "privileges of the author creating the procedure", so without taking into account the acquired privileges through roles... Your user name is 'sequence create' through a role, it cannot use the privilege within the procedure.  But... but when you define the procedure with AUTHID CURRENT_USER, privileges are evaluated at run time, and thanks to the active ROLE in the session by calling the procedure, at this time, the user can create the sequence.  If try again you but with 'The VALUE NONE ROLE' in the session before the call, you will again have the question.

    Conclusion: If you need to do the action, you must grant the user the necessary privilege directly.

    Best regards

    Bruno Vroman.

Maybe you are looking for

  • iPad 3 loads slow

    Hello 3 iPad from my friend is in slow charge even when it is off. did you guys of the clues? p.s. the accusations of the iPad with a third party adapter cable and usb power

  • Magnetic car holder. Can it damage my iPhone?

    Recently I bought a magnet for car and I want to know if this unit can damage my iPhone. Thank you.

  • UEFI on Yoga 2 13 password?

    Hello I bought a new laptop Yoga 2 13 and I'm trying to access the configuration of the UEFI. But my computer asks me a password. I have never set one up, is it a universal password? Who put it there? The company who sold me the computer or Lenovo? T

  • Error code 80070539 will not install in new Windows Pro 32

    Starts to install, allows you to restore and shortly after "updates could not be installed" I closed Google desktop, 3rd party antivirus paused and have nothing else running.  Will have some problem installing HP 6 L printer and get other software to

  • I'm having problems with outlook 6 says name of user and password

    I'm trying to implement outlook6 so I can send an email to craigslist. What is my username and passsword?