Domanda

I at trying to create trigger with the following code.

CREATE OR REPLACE TRIGGER MYTABLE_TRG 
BEFORE INSERT ON MYTABLE 
FOR EACH ROW 
BEGIN 
 select MYTABLE_SEQ.nextval into :new.id from dual; 
END;

I am getting error

Error(2,52): PLS-00049: bad bind variable 'NEW.ID'

Any ideas? Thanks.

È stato utile?

Soluzione

It seems like the error code is telling you there's no such column ID in your table...

Altri suggerimenti

Somehow your environment is treating your code as SQL instead of a DDL statement. This works for me (running in sqlplus.exe from a command prompt):

SQL> create sequence mytable_seq;

Sequence created.

SQL> create table mytable (id number);

Table created.

SQL> CREATE OR REPLACE TRIGGER MYTABLE_TRG
  2  BEFORE INSERT ON MYTABLE
  3  FOR EACH ROW
  4  BEGIN
  5   select MYTABLE_SEQ.nextval into :new.id from dual;
  6  END;
  7  /

Trigger created.

Note the trailing "/" - this might be important in the application you are compiling this with.

if one would use proper naming convention the spotting of this type of errors would be much easier ( where proper means using pre- and postfixes ) for generic object names hinting about their purpose better i.e. something like this would have spotted the correct answer

  --START -- CREATE A SEQUENCE
  /*
  create table "TBL_NAME" (
     "TBL_NAME_ID"      number(19,0) NOT NULL 
    , ... 
  */  
  --------------------------------------------------------
  --  drop the sequence if it exists
  -- select * from user_sequences ; 
  --------------------------------------------------------
  declare
     c int;
  begin
     select count(*) into c from user_sequences 
      where SEQUENCE_NAME = upper('SEQ_TBL_NAME');
     if c = 1 then
        execute immediate 'DROP SEQUENCE SEQ_TBL_NAME';
     end if;
  end;
  /

  CREATE SEQUENCE  "SEQ_TBL_NAME"  
  MINVALUE 1 MAXVALUE 999999999999999999999999999 
  INCREMENT BY 1 START WITH 1 
  CACHE 20 NOORDER  NOCYCLE ;


  -- CREATE  
  CREATE OR REPLACE TRIGGER "TRG_TBL_NAME" 
  BEFORE INSERT
  ON "TBL_NAME"
  REFERENCING NEW AS New OLD AS Old
  FOR EACH ROW
  DECLARE
  tmpVar NUMBER;

  BEGIN
     tmpVar := 1 ;

     SELECT SEQ_TBL_NAME.NEXTVAL INTO tmpVar FROM dual;
     :NEW.TBL_NAME_ID := tmpVar;

  END TRG_TBL_NAME; 
  /
  ALTER TRIGGER "TRG_TBL_NAME" ENABLE;
  -- STOP  -- CREATE THE TRIGGER

If you're like me and your code should be working, try dropping the trigger explicitly before you re-create it. Stupid Oracle.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top