10

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.

4 Answers4

20

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

DCookie
  • 42,630
  • 11
  • 83
  • 92
0

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.

JoshL
  • 10,737
  • 11
  • 55
  • 61
0

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
Community
  • 1
  • 1
Yordan Georgiev
  • 5,114
  • 1
  • 56
  • 53
0

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

Hugh Seagraves
  • 594
  • 1
  • 8
  • 14