Help on Trigger

Hi All,
Create or Replace trigger store_master_trigger
after insert on store_transaction
Referencing old as old new as new
For each row
Begin
update store_master
set chemical_balance =:old.chemical_balance -:new.chemical_balance
where chemical_id=:new.chemical_id;
SQL> desc store_transaction;
Name Null? Type
CIRCLE_NUMBER NUMBER(2)
CHEMICAL_ID NUMBER(2)
TRANS_TYPE VARCHAR2(10)
TRANS_QTY NUMBER(5)
TRANS_DATE DATE
SQL> desc store_master;
Name Null? Type
CHEMICAL_ID NOT NULL NUMBER(2)
CHEMICAL_NAME NOT NULL VARCHAR2(30)
CHEMICAL_BALANCE NOT NULL NUMBER(5)
CHEMICAL_UNIT NOT NULL VARCHAR2(8)
RECEIPT_DATE DATE
After creating trigger I am getting error .
PLS-00049 : Bad bind variable 'OLD.CHEMICAL_BALANCE'
PLS-00049 : Bad bind variable 'NEW.CHEMICAL_BALANCE'
Can any one help me to sort out this problem ..
Thanks in advance ..
Sachin

set chemical_balance =:old.chemical_balance -:new.chemical_balance
set chemical_balance = chemical_balance - nvl(:new.TRANS_QTY, 0) -- :)))

Similar Messages

  • Help with trigger

    Dear All,
    I have a trigger that works fine when the value is updated by a user but when the value is updated by another trigger it does not seem to work.
    When i log in and update the value in sqlplus it works fine but when I update a value in another table which then calls a trigger which then updates that value in the main table the trigger does not fire.
    This is the scenario. We have a table called payments. When we run a process it sets some values in this payment table.
    When this value is set in the payments table it fires a trigger which then updates the invoice table (paid_date) based on some value in the payments table.
    Now when this value in the invoices table is set by the trigger it is meant to call another trigger which should recognise this new value but this does not hapen.
    however if i go in manually and update the invoice table, the trigger fires.
    Any help will be appreciated.
    Below is the trigger that does not seem to fire.
    I have also included the trigger which sets this value
    create or replace
    TRIGGER INVOICE_PAID before
    UPDATE OF "PAID_DATE" ON "INVOICES" FOR EACH ROW
    DECLARE
    -- check if the invoice.mco_transfer_status has been updated to R
    -- if it has then insert records into the relevant tables
    -- Start the Insert based on the update of invoices.mco_transfer_status
    fa_cnt PLS_INTEGER;
    ecode VARCHAR2(100);
    thisproc CONSTANT VARCHAR2(80) := 'trap_errmesg for mco_transfer_status';
    v_value VARCHAR2(150);
    BEGIN
    -- do updates based on update of invoices.transfer_status column
    IF :NEW.PAID_DATE IS NOT NULL AND :OLD.PAID_DATE IS NULL
    THEN
    :NEW.MCO_TRANSFER_STATUS := 'R';
    :NEW.TRANSFER_STATUS:='R';
    :NEW.RECONCILED_STATUS:='R';
    INSERT INTO EMCO_INVOICE_STAGE (emco_document_number,invoice_id,raised_date,paid_date,pnr_reference,booking_date,
    gross,currency,forename,surname)
    SELECT :NEW.EMCO_DOCUMENT_NUMBER,:NEW.INVOICE_ID,:NEW.RAISED_DATE,:NEW.PAID_DATE,BK.PNR_REFERENCE,BK.BOOKING_DATE,:NEW.GROSS,
    :NEW.CURRENCY,PX.FORENAME,PX.SURNAME
    FROM BOOKINGS BK, PAX PX
    WHERE BK.BOOKING_ID=:NEW.BOOKING_ID
    AND PX.BOOKING_ID=:NEW.BOOKING_ID AND
    PX.PAX_SEQ=(SELECT MIN(px2.pax_seq) FROM PAX px2 WHERE booking_id=:NEW.BOOKING_ID AND px2.status <>'X' AND px2.pax_type='A' );
    -- Insert into PAYMENTS_STAGE table
    INSERT INTO PAYMENTS_STAGE (EMCO_DOCUMENT_NUMBER, PAYMENT_ID, INVOICE_ID, PAYMENT_DATE,PAYMENT_TYPE,AMOUNT,
    CURRENCY,CARD_NUMBER,TRANSACTIONID)
    SELECT :NEW.EMCO_DOCUMENT_NUMBER,PAYMENT_ID,INVOICE_ID,PAYMENT_DATE,PAYMENT_TYPE,AMOUNT,CURRENCY,CC.CARD_NUMBER,TRANSACTIONID
    FROM PAYMENTS PA, CREDIT_CARDS CC
    WHERE PA.INVOICE_ID=:NEW.INVOICE_ID
    AND CC.CARD_ID = PA.CARD_ID;
    :NEW.MCO_TRANSFER_STATUS:='C';
    SELECT COUNT(*) INTO fa_cnt FROM INVOICE_DETAILS WHERE
    invoice_id=:NEW.INVOICE_ID AND CHARGE_TYPE='FA';
    IF fa_cnt > 0
    THEN :NEW.TICKETING_STATUS:='R';
    ELSE
    :NEW.TICKETING_STATUS:='N';
    :NEW.EXCHANGED_DATE := :NEW.PAID_DATE;
    END IF;
    END IF;
    EXCEPTION
    WHEN OTHERS THEN
    ecode := SQLCODE|| ' '||SQLERRM ;
    dbms_output.put_line(thisproc || ' - ' || ecode);
    v_value := thisproc || ' - ' || ecode;
    INSERT INTO DOCUMENT_STATUS_STAGE (EMCO_DOCUMENT_NUMBER, STATUS,STATUS_DATE)
    VALUES (:NEW.EMCO_DOCUMENT_NUMBER,v_value,SYSDATE);
    :NEW.MCO_TRANSFER_STATUS := 'F';
    END INVOICE_PAID;
    TRIGGER "CAM_OWNER"."CHECK_INVOICE_PAID_IN_FULL" AFTER
    UPDATE OF "PAYMENT_STATUS" ON "CAM_OWNER"."PAYMENTS"
    DECLARE
    -- check if all the payments for that invoice have been received (completed)
    -- if they are complete then sum all the payments for that invoice and compare to gross value on invoices
    v_invoice_amount NUMBER;
    v_gross_amount NUMBER;
    thisproc CONSTANT VARCHAR2(80) := 'trap_errmesg for mco_transfer_status';
    v_value VARCHAR2(150);
    BEGIN
    -- Changed as requested by nicola on 12/09/05 IF :NEW.PAYMENT_COMPLETE is not null
    --IF :NEW.PAYMENT_STATUS='C' AND :NEW.PAYMENT_STATUS <> :OLD.PAYMENT_STATUS
    --THEN
    CHECK_INVOICE_PAID_IN_FULL_PRO;
    --END IF;
    END CHECK_INVOICE_PAID_IN_FULL;
    and this is the procedure that is called
    PROCEDURE "CHECK_INVOICE_PAID_IN_FULL_PRO" IS
    -- check if all the payments for that invoice have been received (completed)
    -- if they are complete then sum all the payments for that invoice and compare to gross value on invoices
    v_invoice_amount NUMBER(20);
    v_gross_amount NUMBER(20);
    thisproc CONSTANT VARCHAR2(80) := 'trap_errmesg for mco_transfer_status';
    v_value VARCHAR2(150);
    BEGIN
    -- We will sum all the payments for that invoice that have a value in payment_complete
    --select sum(amount) into v_invoice_amount from payments where payment_complete is not null and invoice_id=:NEW.INVOICE_ID;
    FOR x IN (SELECT invoice_id FROM PAYMENTS_TEMP) LOOP
    SELECT NVL(SUM(amount),0) INTO v_invoice_amount FROM PAYMENTS
    WHERE payment_status ='C' AND invoice_id=X.INVOICE_ID;
    SELECT NVL(gross,0) INTO v_gross_amount FROM INVOICES WHERE
    invoice_id =X.INVOICE_ID;
    -- We will also get the gross amount for the invoice to compare to the sum of the payments
    IF v_invoice_amount = v_gross_amount
    THEN
    UPDATE INVOICES SET paid_date=SYSDATE
    WHERE invoice_id=X.INVOICE_ID;
    END IF;
    END LOOP;
    END CHECK_INVOICE_PAID_IN_FULL_PRO;

    The following demonstration is a direct response to your original question, in case you want to stick with that method of scheduling your index rebuilds through a trigger. In order to do ddl like alter index you will need to use dynamic sql like execute immediate. Since you can't rebuild the index before the insert or update has been committed, you will need to use dbms_job.submit to schedule the rebuild. In the following example, the index rebuild will be done as soon as the insert or update has been committed.
    scott@ORA92> CREATE TABLE cc_contenidos (cvalor CLOB)
      2  /
    Table created.
    scott@ORA92> CREATE INDEX cont ON cc_contenidos (cvalor) INDEXTYPE IS ctxsys.context
      2  /
    Index created.
    scott@ORA92> SELECT last_ddl_time FROM user_objects WHERE object_name = 'CONT'
      2  /
    LAST_DDL_TIME
    24-JAN-2005 21:10:13
    scott@ORA92> CREATE OR REPLACE PROCEDURE alter_index_cont
      2  AS
      3  BEGIN
      4    EXECUTE IMMEDIATE 'ALTER INDEX cont REBUILD ONLINE PARAMETERS (''sync memory 45M'')';
      5  END;
      6  /
    Procedure created.
    scott@ORA92> SHOW ERRORS
    No errors.
    scott@ORA92> CREATE OR REPLACE TRIGGER actualiza
      2    AFTER DELETE OR INSERT OR UPDATE on cc_contenidos
      3  DECLARE
      4    v_job NUMBER;
      5  BEGIN
      6    DBMS_JOB.SUBMIT (v_job, 'alter_index_cont;', SYSDATE);
      7  END actualiza;
      8  /
    Trigger created.
    scott@ORA92> SHOW ERRORS
    No errors.
    scott@ORA92> INSERT INTO cc_contenidos (cvalor) VALUES ('test 1')
      2  /
    1 row created.
    scott@ORA92> INSERT INTO cc_contenidos (cvalor) VALUES ('test 2')
      2  /
    1 row created.
    scott@ORA92> COMMIT
      2  /
    Commit complete.
    scott@ORA92> EXECUTE DBMS_LOCK.SLEEP (15)
    PL/SQL procedure successfully completed.
    scott@ORA92> SELECT last_ddl_time FROM user_objects WHERE object_name = 'CONT'
      2  /
    LAST_DDL_TIME
    24-JAN-2005 21:10:17
    scott@ORA92> SELECT * FROM cc_contenidos WHERE CONTAINS (cvalor, 'test') > 0
      2  /
    CVALOR
    test 2
    test 1
    scott@ORA92>

  • Need Urgent Help with trigger in Oracle 10g

    Hello frd,
    I am working on my DBMS Project in VB 6.0 that is Tollbooth management system
    i have to insert one trigger for my project so i had decided to insert time trigger.
    I have total 3 table UserLogin, Vehice and Vehicle_Data
    the 3rd table Vehicle data contain the following fields
    Vehicle_Type, Vehicle_No, Tax_Time, Source, Destination and Tax
    Now i had done coding for tax when you select Vehicle Type, Source and Destination the Tax Field will automatically fillup and all the data will Saved in Oracle table but now my problem is that i want to create trigger for Tax_Time column When any new data inserted current time will stored in that column
    I had create one but it gives error
    create trigger time after insert on vehicle_Data
    for each row
    begin
    insert into Vehicle_Data(Tax_Time) values(to_char(sysdate, 'HH:MI:SSAM DD_MON_YYYY'));
    end;
    Note: I am Using VB 6.0 and Oracle 10g Express Edition

    I had create one but it gives errorWelcome to the forum and many many thanks for not posting the full error message, that is really helpful, since we're all a 100% sure what's going on now (yes, that was ironic ;) ).
    Let me guess: a mutating table error?
    Read:
    http://www.oracle-base.com/articles/9i/MutatingTableExceptions.php
    http://asktom.oracle.com/pls/asktom/ASKTOM.download_file?p_file=6551198119097816936
    But before that, actually you should read:
    http://tkyte.blogspot.com/2005/06/how-to-ask-questions.html

  • Need help with trigger for whitespace and caps validation

    I need to create a table trigger that will generate an error whenever a specific column does not contain all caps or has whitespace when records are either inserted or updated. I'm new to writing SQL, so any help is appreciated!

    In 10g
    SQL> create or replace trigger trigg_sample
      2  before update or insert on sample
      3  for each row
      4  declare
      5  lv_pos number;
      6  begin
      7  select regexp_instr(:new.col1,'[a-z|( )]') into lv_pos from dual;
      8  if lv_pos > 0 then
      9  raise_application_error(20000,'The column contains lowercase or white space characters');
    10  end if;
    11  end;
    12  /
    Trigger created.
    SQL> desc sample;
    Name                                      Null?    Type
    COL1                                               VARCHAR2(20)
    SQL> insert into sample values('DFD') ;
    1 row created.
    SQL> insert into sample values('dfdfd') ;
    insert into sample values('dfdfd')
    ERROR at line 1:
    ORA-21000: error number argument to raise_application_error of 20000 is out of
    range
    ORA-06512: at "XLS_ADMIN.TRIGG_SAMPLE", line 6
    ORA-04088: error during execution of trigger 'XLS_ADMIN.TRIGG_SAMPLE'
    SQL> insert into sample values('DFDF ') ;
    insert into sample values('DFDF ')
    ERROR at line 1:
    ORA-21000: error number argument to raise_application_error of 20000 is out of
    range
    ORA-06512: at "XLS_ADMIN.TRIGG_SAMPLE", line 6
    ORA-04088: error during execution of trigger 'XLS_ADMIN.TRIGG_SAMPLE'
    SQL>

  • Help for trigger

    i have two tables asset and feature.whenever i insert data into feature the trigger should automatically retrieve the asset_id from asset table and insert it.
    these are the tables.
    SQL> desc feature;
    Name Null? Type
    ASSET_ID NOT NULL NUMBER(11)
    SITE_SECTION NOT NULL VARCHAR2(50)
    HED NOT NULL VARCHAR2(256)
    CONTENT_FORMAT NOT NULL VARCHAR2(256)
    DEK VARCHAR2(256)
    TOUT NOT NULL VARCHAR2(1024)
    PUBLISH_DATE NOT NULL DATE
    IMAGE_URL VARCHAR2(512)
    FRAGMENT_PATH NOT NULL VARCHAR2(1024)
    VPATH VARCHAR2(1024)
    SQL> desc asset;
    Name Null? Type
    ASSET_ID NOT NULL NUMBER(11)
    ASSET_TYPE_ID NOT NULL NUMBER(11)
    CREATE_DT NOT NULL DATE
    UPDATE_DT DATE
    EXPR_DT DATE
    TITLE VARCHAR2(256)
    SR_SUMMARY VARCHAR2(1024)
    CODEWORD VARCHAR2(1024)
    VPATH NOT NULL VARCHAR2(1024)
    AUTHOR VARCHAR2(100)
    this is the trigger i have written
    CREATE OR REPLACE TRIGGER INSERTFEATURE_ASSETID BEFORE INSERT ON
         FEATURE FOR EACH ROW
    BEGIN
    SELECT ASSET_ID into :NEW.ASSET_ID FROM ASSET WHERE ASSET_TYPE_ID = 15 AND VPATH
    = :NEW.VPATH;
    insert into feature(asset_id) values(:new.asset_id);
    END;
    when i am inserting data into feature with
    insert into feature(site_section,hed,content_format,tout,publish_date,fragment_path,vpath)
    values('asdf','acv','aaaa','aaaa',TO_DATE('06/06/1985','MM/DD/YYYY'),'qqqq','/even/more/paths');
    it is saying no data found and error at the trigger in line 4;
    where there is appropriate data in the asset table
    SQL> select asset_id from asset where vpath='/some/other/path' and asset_type_id=15;
    4
    please help me.

    thank you,
    but if i have the trigger like this
    CREATE OR REPLACE TRIGGER INSERTFEATURE_ASSETID BEFORE INSERT ON
         FEATURE FOR EACH ROW
    BEGIN
    SELECT ASSET_ID into :NEW.ASSET_ID FROM ASSET WHERE ASSET_TYPE_ID = 15 AND VPATH
    = :NEW.VPATH;
    END;
    and
    SQL> insert into feature(site_section,hed,content_format,tout,publish_date,fragment_path,vpath)
    2 values('asdf','acv','aaaa','aaaa',TO_DATE('06/06/1985','MM/DD/YYYY'),'qqqq','/even/more/paths')
    insert into feature(site_section,hed,content_format,tout,publish_date,fragment_path,vpath)
    ERROR at line 1:
    ORA-00001: unique constraint (BEDEV.PK_FEATURE_ASSET_ID) violated
    this is the problem i am getting

  • Please Help With Trigger

    I posted about this trigger earlier but have worked on it and got a little further along.
    Here is my trigger
    CREATE OR REPLACE TRIGGER trigger_session_check
    BEFORE INSERT OR UPDATE OF session_date, patient_id ON sessions
    FOR EACH ROW
    DECLARE
         v_no_of_errors NUMBER;
         consecutive_error EXCEPTION;
    BEGIN
         SELECT MAX(COUNT(*))
         INTO v_no_of_errors
         FROM sessions
         WHERE session_date > :new.session_date - interval '4' hour
         AND patient_id = :new.patient_id
         GROUP BY session_date, patient_id
         HAVING COUNT(*) > 1;
         IF v_no_of_errors IS NOT NULL THEN
         RAISE consecutive_error;
         END IF;
         EXCEPTION
    WHEN consecutive_error THEN
    RAISE_APPLICATION_ERROR(-20000, 'PATIENT HAS A PREVIOUS SESSION BOOKED THAT IS 4 HOURS OR LESS BEFORE OR AFTER THIS BOOKING');
    END;
    It identifies an identical booking but does not recognise time changes. I need to stop sessions being booked that are 4 hours or less before and after any session that has been booked for a patient.
    Here is my table
    create table sessions
    (session_id int not null,
    patient_id int not null references patient,
    treatment_id int not null references treatment,
    treatmentroom_id int not null references treatmentroom,
    specialist_id int not null references specialist,
    assistant_id int not null references assistant,
    session_date timestamp (0),
    primary key (session_id));
    CREATE SEQUENCE sessionid_seq
    MINVALUE 1000
    INCREMENT BY 1
    MAXVALUE 100000;
    and here is a sample insert
    insert into sessions values (sessionID_seq.NextVal, 12, 2, 109, 115, 129, to_timestamp('02-DEC-2005 19:00:00', 'DD-MON-YYYY HH24:MI:SS'));
    Please help me with identiffying the interval within my where clause, as it is slowing driving me mad.
    Message was edited by:
    user470897

    As promised, please find thereafter the trigger code.
    The problem to solve is that the trigger doesn't see the non committed modification because it is part of another transaction. So the row is seen as not modified by the trigger and this issue must be treated.
    With "insert" there is nothing old to worry about. With "update", we have to take away the modified row from the result to check.
    CREATE OR REPLACE TRIGGER trigger_session_check
    BEFORE INSERT OR UPDATE OF session_date, patient_id ON sessions
    FOR EACH ROW
    DECLARE
      PRAGMA AUTONOMOUS_TRANSACTION;
      c_lock_name CONSTANT VARCHAR2(30) := 'trigger_session_check_lock';
      v_id VARCHAR2(128);
      v_status INTEGER;
      v_no_of_errors NUMBER;
      consecutive_error EXCEPTION;
    BEGIN
      -- genrates a unique identifier for the lock or use the one already generated
      dbms_lock.allocate_unique(c_lock_name, v_id);
      -- I used a timeout of six minutes and the lock will be released when we commit
      v_status := dbms_lock.request(v_id, dbms_lock.ssx_mode, 360, true);
      IF UPDATING THEN
        SELECT COUNT(*)
        INTO v_no_of_errors
        FROM sessions
        WHERE session_date - Interval'4' hour < :new.session_date
             AND session_date - Interval'-4' hour > :new.session_date
             AND patient_id = :new.patient_id
             AND session_date != :old.session_date ;
      END IF;
      IF INSERTING THEN
        SELECT COUNT(*)
        INTO v_no_of_errors
        FROM sessions
        WHERE session_date - Interval'4' hour < :new.session_date
             AND session_date - Interval'-4' hour > :new.session_date
             AND patient_id = :new.patient_id;
      END IF;
      IF v_no_of_errors > 0 THEN
         RAISE consecutive_error;
      END IF;
      COMMIT;
    EXCEPTION
       WHEN consecutive_error THEN
          RAISE_APPLICATION_ERROR(-20000, 'PATIENT HAS A SESSION BOOKED THAT IS 4 HOURS OR LESS BEFORE OR AFTER THIS ONE');
    END;
    /

  • Help in trigger creation

    Hi guys,
    I am using oracle 10g on windows 2003 server.
    I have two tables namely PEOPLE and UG_COMMAND.
    There are two columns in People table- STAFF_CODE and USER_29. I want to create a trigger which should check if STAFF_CODE is null and
    USER_29 is not null. On meeting this condition it should populate command column of UG_COMMAND table.
    Thanks for help!!

    Hi
    Create or replace trigger people_trrg
    after insert on people for each row
    REFERENCING NEW AS NEW OLD AS OLD
    FOR EACH ROW
    BEGIN
    if :new.user_29 is not null then
    if :new.staff_code is null then
    Insert into UG_Command (command) values ('some value');
    else
    Insert into UG_Command (command) values ('some value');----this will kick in if the value is not null
    end if;
    end if;
    EXCEPTION
        WHEN others THEN Raise;
    END;Note: If there are some other not null columns in UG_command, then the trigger will fail, you need to include all not null columns
    HTH

  • Help in Trigger ( When-radio-changed )

    Hi,
    I have a form which represents a sales invoice and I have an item called (pay_type) It’s a radio group included  (cash , debit, cheque, .. so on )
    now for EX if the user choose ‘cash’
    It supposed the trigger takes the invoice value and ( + ) it on the Treasury table  (this is fixed)
    And on the other hand it should (–) the invoice items quantities from the ( store_item ) table
    And this is the problem I need help in, because I couldn't write the where condition to decrease the quantities from store_item table based on the ( item_code & store_code ) Which in the invoice.
    i tried this code and i know that "the where condition is wrong here" but i try to show u what i need to do
    begin
    if :pay_type = 'cash'
    then
    update cash
    set cash.balance = cash.balance + :inv_detail.net_val;
    update store_item
    set store_item.quantity = store_item.quantity - :inv_detail.quantity
    where inv_detail.item_code = store_item.item_code;
    elsif
    :pay_type = 'debit'
    then update customer
       set customer.debit_val = customer.debit_val + :inv_detail.net_val;
    end if;
    end;
    And this is the scripts for 5 tables with columns I think u just need & sample data
    2 of them are about the invoice
    3-item table         4-store table         
    5- store_item ”this is created to handle the many to many relationship between (item & store ) tables”
    --item table
    CREATE TABLE ITEM
    ( ITEM_CODE        NUMBER,
      ITEM_NAME        VARCHAR2(100 BYTE),
      COST             NUMBER(10,2),
      PRICE            NUMBER(10,2));
    ALTER TABLE ITEM ADD (CONSTRAINT ITEM_PK  PRIMARY KEY (ITEM_CODE) ENABLE VALIDATE) ;
    Insert into ITEM
       (ITEM_CODE, ITEM_NAME, COST, PRICE)
    Values
       (1, 'keyboard dell usb', 20, 25);
    --STORE TABLE
    CREATE TABLE STORE
    (STORE_CODE         NUMBER,
      STORE_NAME         VARCHAR2(100 BYTE)         NOT NULL);
    ALTER TABLE STORE ADD (CONSTRAINT STORE_PK PRIMARY KEY (STORE_CODE) ENABLE VALIDATE);
    Insert into STORE
       (STORE_CODE, STORE_NAME)
    Values (1,'aa');
    Insert into STORE
       (STORE_CODE, STORE_NAME)
    Values (2,'bb');
    --STORE_ITEM table
    CREATE TABLE STORE_ITEM
    (STORE_CODE  NUMBER,
      ITEM_CODE   NUMBER,
      QUANTITY    NUMBER(10,2));
    ALTER TABLE STORE_ITEM ADD (CONSTRAINT STORE_ITEM_PK PRIMARY KEY (STORE_CODE, ITEM_CODE) ENABLE VALIDATE);
    ALTER TABLE STORE_ITEM ADD (CONSTRAINT ITEM_STOREITEM_CODE FOREIGN KEY (ITEM_CODE) REFERENCES ITEM (ITEM_CODE) ENABLE VALIDATE,
      CONSTRAINT STORE_STOREITEM_CODE FOREIGN KEY (STORE_CODE) REFERENCES STORE (STORE_CODE) ENABLE VALIDATE);
    Insert into STORE_ITEM
       (STORE_CODE, ITEM_CODE, QUANTITY)
    Values (1, 1, 250);
    Insert into STORE_ITEM
       (STORE_CODE, ITEM_CODE, QUANTITY)
    Values (2, 1, 500);
    --INV_HEADER  table
    CREATE TABLE INV_HEADER
    (SERIAL_NO        NUMBER(10),
      INV_DATE         DATE                         NOT NULL,
      STORE_INVH_CODE  NUMBER);
    ALTER TABLE INV_HEADER ADD (CONSTRAINT INV_HEADER_PK PRIMARY KEY (SERIAL_NO) ENABLE VALIDATE);
    ALTER TABLE INV_HEADER ADD (CONSTRAINT STORE_INVH_FK FOREIGN KEY (STORE_INVH_CODE)  REFERENCES STORE (STORE_CODE) ENABLE VALIDATE);
    --INV_DETAIL table
    CREATE TABLE INV_DETAIL
    ( SEQ               NUMBER,
      ITEM_CODE         NUMBER,
      ITEM_NAME         VARCHAR2(100 BYTE),
      QUANTITY          NUMBER(10,2),
      NET_VAL           NUMBER(10,2),
      PAY_TYPE          VARCHAR2(50 BYTE),
      INVH_INVD_SERIAL  NUMBER(10));
    ALTER TABLE INV_DETAIL ADD (CONSTRAINT INV_DETAIL_PK PRIMARY KEY (ITEM_CODE) ENABLE VALIDATE);
    ALTER TABLE INV_DETAIL ADD (CONSTRAINT INVH_INVD_FK FOREIGN KEY (INVH_INVD_SERIAL) REFERENCES INV_HEADER (SERIAL_NO) ENABLE VALIDATE);
    -- i'll be grateful if anyone could help me in this
    --Thanks

    create database trigger in salesta table and
    begin
    if :pay_type = 'cash'
    then
    update cash
    set cash.balance = cash.balance + :inv_detail.net_val;
    update store_item
    set store_item.quantity = store_item.quantity - :inv_detail.quantity
    where inv_detail.item_code = store_item.item_code;
    elsif
    :pay_type = 'debit'
    then update customer
       set customer.debit_val = customer.debit_val + :inv_detail.net_val;
    end if;
    end;

  • Need help with trigger/new at pl/sql

    I would appreciate any help as I am new to PL/SQL and have run out of ideas.
    I am trying to write a trigger that when a user inserts a row into a table that records an ID, a clinic, and user initials, a second table is updated with that ID in the next available "slot" for that clinic.
    I wrote a procedure that does execute successfully with ID, user initials, and clinic hardcoded. I cannot create a trigger using the fields from the 1st table instead of the hardcoded values that compiles without errors.
    The tables in question are in another schema, but I have all priviledges on that schema.
    I have tried referencing the fields from table 1 in every way I can think of:
    1) :new.<field from table 1> and got:
    ORA-04082: NEW or OLD references not allowed in table level triggers
    2) :<field from table 1> and got
    PLS-00049: bad bind variable '<field name>'
    3) <field from table 1> , <table>.<field from table 1>, <schema>.<table>.<field from table> and got
    5/38 PL/SQL: ORA-00904: "N106CLINIC": invalid identifier
    14/44 PL/SQL: ORA-00904: "N106CLINIC": invalid identifier
    and
    5/38 PL/SQL: ORA-00904: "N106"."N106CLINIC": invalid identifier
    14/44 PL/SQL: ORA-00904: "N106"."N106CLINIC": invalid identifier
    and
    5/38 PL/SQL: ORA-00904: "CCRN"."N106"."N106CLINIC": invalid identifier
    14/44 PL/SQL: ORA-00904: "CCRN"."N106"."N106CLINIC": invalid identifier
    in addition to "SQL statement ignored".
    It does complain only about n106clinic, even though other fields referenced from the first table are n106id and n106init; n106clinic IS a valid field name in the n106 table...maybe this is just a compiler peculiarity.
    Here is the code for the trigger. N106 is the table where the user inserts a row and RAMBCYL is the table to be updated. CCRN is the schema that owns the two tables.
    create or replace trigger ccrn.aocylrand
    after insert
    on ccrn.n106
    declare l_accno number;
    begin
    select rambcyl.accno into l_accno
    from ccrn.rambcyl rambcyl
    where rambcyl.clinic=n106clinic and
    rambcyl.accno = (select min(r.accno)
    from ccrn.rambcyl r
    where r.id is null
    and r.clinic = n106clinic);
    update ccrn.rambcyl set id =n106id,
    randdt = sysdate,
    staff=n106init
    where ccrn.rambcyl.accno = l_accno and
    ccrn.rambcyl.clinic = n106clinic;
    end aocylrand;
    Thanks, Helen

    You cannot refer to the :old or :new column values in a statement level trigger, only in row-level triggers. I would suggest the following which does the update in a single statement:
    create or replace trigger ccrn.aocylrand
      after insert
      on ccrn.n106
      for each row  -- specifies a row-level trigger
    begin
      update ccrn.rambcyl r1
         set id = :new.n106id,
             randdt = sysdate,
             staff = :new.n106init
       where clinic = :new.n106clinic
         and accno = (select min(r2.accno)
                        from ccrn.rambcyl r2
                       where r2.id is null
                         and r2.clinic = r1.clinic);
    end aocylrand;

  • Need help on trigger...

    i'm the beginner in Oracle, need help on below.
    can i use statement like "Select count..." in the before and after update trigger?
    i have the "mutating" error when i create the trigger...
    pls help

    correction - there is no error generated when compile the trigger but errors when the trigger is fired:
    /* perform updating on table student*/
    update student set company_id = 60 where student_id = 9998;
    /* error return by oracle sql plus*/
    at line 1:
    4091: table SCOTT.STUDENT is mutating, trigger/function may not see it
    6512: at "SCOTT.UST_UPDPASSPORTPROGRAM", line 7
    6512: at "SCOTT.UST_UPDPASSPORTPROGRAM", line 9
    4088: error during execution of trigger 'SCOTT.UST_UPDPASSPORTPROGRAM'
    /* trigger script*/
    create or replace trigger ust_updPassportProgram
    before update
    on student
    for each row
    declare
    v_total_Student number;
    Dummy number;
    /*CURSOR Dummy_cursor (CNo NUMBER) IS*/
    /*SELECT company_id FROM company WHERE company_id = CNo;*/
    CURSOR Dummy_cursor (CNo NUMBER) IS
    SELECT student_id FROM student WHERE student_id = 9998 and company_id = CNo;
    begin
    OPEN Dummy_cursor (:new.company_id);
    FETCH Dummy_cursor INTO Dummy;
    IF Dummy_cursor%FOUND THEN
    dbms_output.put_line('Dummy found');
    end if;
    if :new.passport_program = 'Y' then
    dbms_output.put_line('The current company_id: ' ||
    to_char(:new.company_id) || :new.passport_program);
    end if;
    end;
    /

  • I need help! TRIGGER PROBLEM.

    I have a case where I am checking for conflict do to date/times in table "MAINT".
    if an ID that is changed or added in table "SCHEDULE", I need to change the corresponding id in table MAINT, if that change make the id go into conflict, meaning that the start_time and the end_time of the NEW record is in the start and end time of the :OLD record, then I set the conlict flag in the MAINT table to "Y". If the change takes an ID out of conflict, then I set the conflict flag in the MAINT table to "N". Basically my algorithm is:
    1. get the OLD.id conflict record
    2. get a cursor of all records except the old id conflict record.
    3. compare the old id conflict recordd start and end times in the cursor, if there is a conflict in times, then update the record in the cursor and the old_id conlict to 'Y'.
    4. get the new_id record (the one that changed).
    5. Get the cursor of the new id records except the one that changed.
    6. compare the new record to the cursor start and end times.
    7. If conflict, update the new record and the one that it has a conflict with.
    8. if not a conflict, update the new record.
    I hope you can figure out what I am trying to say in a a generic sort of way.

    I am sorry...
    The trigger that I tried to come up with is:
    CREATE OR REPLACE TRIGGER trgupdate_resource_id AFTER
    UPDATE OF resource_id ON maintenance_resource_req FOR EACH ROW
    DECLARE pragma autonomous_transaction;
    BEGIN
    UPDATE resource_schedules
    SET resource_schedules.resource_id = :NEW.resource_id
    WHERE resource_schedules.resource_id = :OLD.resource_id
    AND resource_schedules.maintenance_id = :OLD.maintenance_id
    AND resource_schedules.step_number = :OLD.step_number;
    IF :OLD.resource_id = :NEW.resource_id THEN
    IF :OLD.maintenance_id = :NEW.maintenance_id THEN
    IF :OLD.step_number = :NEW.step_number THEN
    IF((:NEW.scd_start BETWEEN :OLD.scd_start
    AND :OLD.scd_end)
    AND(:NEW.scd_end BETWEEN :OLD.scd_start
    AND :OLD.scd_end)) THEN
    :NEW.conflict := 'Y'
    ELSE
    :NEW.conflict := 'N'
    END IF;
    END IF;
    END IF;
    END;
    END;
    the table structures:
    "MAINTENANCE_RESOURCE_REQ"
         "MAINTENANCE_ID" NUMBER NOT NULL ENABLE,
         "STEP_NUMBER" NUMBER NOT NULL ENABLE,
         "RESOURCE_ID" NUMBER,
         "PREVIOUS_RESOURCE_ID" NUMBER,
         "CONFLICT" VARCHAR2(1)
    "RESOURCE_SCHEDULES"
    "RESOURCE_SCHED_ID" NUMBER NOT NULL ENABLE,
    "RESOURCE_ID" NUMBER NOT NULL ENABLE,
    "MAINTENANCE_ID" NUMBER,
    "STEP_NUMBER" NUMBER,
    "SCD_START" DATE,
    "SCD_END" DATE
    Sample data:
    RESOURCE_ID START_TIME END_TIME CONFLICT
    1 08:00 09:00 Y
    2 08:00 09:00 N
    3 10:00 11:00 N
    1 08:45 09:15 Y

  • NEED HELP WITH TRIGGER????

    THIS IS TWO TABLE I NEED
    CREATE TABLE "METHODS_LIVE"
    "ID" INTEGER NOT NULL,
    "OBJECTID" INTEGER NOT NULL,
    "LA_KEY" VARCHAR(255) NULL,
    "PROCEDURENAME" VARCHAR(255) NULL,
    "LA_ORDER" INTEGER NOT NULL,
    "TAG" VARCHAR(255) NULL,
    PRIMARY KEY ("ID")
    CREATE TABLE "METHODS_NAME_LIVE"
    "METHODID" INTEGER NOT NULL,
    "LANGUAGE" INTEGER NOT NULL,
    "NAME" VARCHAR(255) NULL,
    PRIMARY KEY ("METHODID", "LANGUAGE")
    ALTER TABLE "METHODS_NAME_LIVE"
    ADD FOREIGN KEY ("METHODID")
    REFERENCES "METHODS_LIVE" ("ID")
    ON DELETE CASCADE;
    I WANT TO REMOVE THE ON DELETE CASCADE AND REPLACE IT BY THIS TRIGGER
    CREATE OR REPLACE trigger tr_del_meth_live before delete
    on METHODS_LIVE referencing old as DELETEDMETHODS_LIVE
    for each row
    begin
    DELETE from METHODS_NAME_LIVE
    where METHODS_NAME_LIVE.METHODID = ELETEDMETHODS_LIVE.ID;
    end;
    WHY I GOT THIS MESSAGES--->
    ORA-04094: table TESTLA2.METHODS_NAME_LIVE is constraining, trigger may not modify it
    ORA-06512: at "TESTLA2.TR_DEL_METH_LIVE", line 5
    ORA-04088: error during execution of trigger 'TESTLA2.TR_DEL_METH_LIVE
    THANK'S

    Remove the foreign key, but u should implement the constraint by yourself in this case or do cascade delete operations on client side.
    null

  • Need help with trigger comp err

    i'm new to forms and triggers. I am trying to do a simple "select into" from the "previous" record so I can see what was the value of a column was and bump it up by one. The code for a post_text_item trigger is:
    select
    anum
    from
    x
    where
    x.pageid = :pageid;
    the gist of the error is that the compile acts like it never heard of table "x", even though the form is built on table "x"! the err is - PDE-PSD001 - Could not resolve ref to unk program unit while loading block ...
    any thoughts??
    thanks in advance,
    Burt
    null

    Sudha -
    actually -
    if the table I mention in the trigger contains an Ordsys.Ordimage column, the trigger blows. I guess the little procedure builder guy cant deal with the intermedia stuff too well/at all. I created a view from the table with the image, but didn't include the image in the view. I referenced the view in the trigger and everything went just fine.
    thanks for your input
    burt
    null

  • Help with Trigger - looping through SELECT results

    How do I loop through a SELECT query within a Custom Trigger? I can
    execute the query fine, but the PHP mysql_xxx_xxx() functions don't
    appear to work inside a custom trigger. For example:
    This ends up empty:
    $totalRows_rsRecordset = mysql_num_rows($rsRecordset);
    While this returns the correct # of records:
    $totalRows_rsRecordset = $rsRecordset->recordCount();
    I need to loop through the records like I would with
    mysql_fetch_assoc(), but those mysql_xxx_xxx() don't seem to work.
    This works great outside a custom trigger, but fails inside a custom
    trigger:
    do {
    array_push($myArray,$row_Recordset['id_usr']);
    while ($row_Recordset= mysql_fetch_assoc($Recordset));
    What am I missing?
    Alec
    Adobe Community Expert

    Although the create trigger documentation does use the word "must", you are quite free to let the trigger fire during a refresh of the materialized view. Generally, you don't want the trigger to fire during a materialized view refresh-- in a multi-master replication environment, for example, you can easily end up with a situation where a change made in A gets replicated to B, the change fired by the trigger in B gets replicated back to A, the change made by the trigger in A gets replicated back to B, in an infinite loop that quickly brings both systems to their knees. But there is nothing that prevents you from letting it run assuming you are confident that you're not going to create any problems for yourself.
    You do need to be aware, however, that there is no guarantee that your trigger will fire only for new rows. For example, it is very likely that at some point in the future, you'll need to do a full refresh of the materialized view in which case all the rows will be deleted and re-inserted (thus causing your trigger to fire for every row). And if your materialized view does anything other than a simple "SELECT * FROM table@db_link", it is possible that an incremental refresh will update a row that actually didn't change because Oracle couldn't guarantee that the row would be unchanged.
    Justin

  • Need help creating trigger with delete capabilities

    I have two tables:
    create table person(userid integer,
    lname varchar(20),
    fname varchar (20),
    phone_number varchar(12),
    email_address varchar(35),
    city varchar(20),
    zip_code varchar(20),
    department varchar(20),
    major_street varchar(20),
    cross_street varchar(20),
    notes varchar(100),
    Primary Key (userid));
    create table vehicle(car_id integer,
    make varchar(15),
    model varchar(20),
    year integer,
    gas_mileage integer,
    capacity integer,
    owner integer,
    primary key (car_id),
    foreign key (owner) references person (userid));
    I am trying to create a trigger that would delete all those records in vehicle whenever someone deletes a record in the person table. Here is the code that I run but it get a compilation error. Here is the the trigger text followed by the error:
    CREATE OR REPLACE TRIGGER ON_DELETE_PERSON
    AFTER DELETE ON person FOR EACH ROW
    BEGIN
    DELETE from vehicle
    where owner=userId;
    END;
    2/4 PL/SQL: SQL Statement ignored
    3/19 PL/SQL: ORA-00904: "USERID": invalid identifier
    Any suggestions?

    CREATE OR REPLACE TRIGGER ON_DELETE_PERSON
    BEFORE DELETE ON person FOR EACH ROW
    BEGIN
    DELETE from vehicle
    where owner=:old.userId;
    END;

Maybe you are looking for

  • Music cd's seem to load but dvd's don't

    Trying to install software from Adobe dvd's (x2 Lightroomm5 and photoshop 12) but just not being recognised - yet inserting music cd starts up iTunes fine..... Also tried film DVD - no avail Any thoughts?

  • Cannot open Lightroom on iMac after download of OS X Yosemite

    After downloading Yosemite on iMac I cannot open Lightroom files. I am getting the message "The Lightroom catalog cannot be used because the parent folder "/" does not allow files to be created within it." Can somebody help me please.

  • Premiere CS5 system - any ideas on this?

    Firstly hello to the forum users as this is my 1st ever question! I am about to purchase a new PC, i need to step up into the 64bit world. Basically I cannot afford exactly what I was planning so as a step towards the right kind of set up I have foun

  • Forced to re-authorize every time I synch my iPod with my computer

    For some reason, the songs I have purchased through the iTunes store fail to download to my iPod whenever I synch. They will be on my iPod when I plug it in, but they are often missing after the synch. The only way I have found around it is to select

  • Need help getting Coscto as a "order prints" option in Elements 12.

    Have already tried refreshing under "Preferences>Adobe Partner Services" several times and downloaded a new "ols_config.xml" file in the "assets" folder. Neither have worked. HELP