Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run multiple scripts one after another in Oracle?

I have the following script:

ALTER TABLE ODANBIRM 
ADD (OBID NUMBER(10, 0) );
----------------------------------------------------------------------------
CREATE OR REPLACE TRIGGER TR_OB_INC 
BEFORE INSERT ON ODANBIRM
FOR EACH ROW 
BEGIN
  SELECT SEQ_OB.NEXTVAL INTO :NEW.OBID FROM DUAL;
END;

-----------------------------------------------------------------------------

DECLARE
CURSOR CUR IS
SELECT ROWID AS RID FROM ODANBIRM;

  RC CUR%ROWTYPE;
BEGIN
  OPEN CUR;

 LOOP
  FETCH CUR INTO RC;

    EXIT WHEN CUR%NOTFOUND;

  UPDATE ODANBIRM SET OBID=SEQ_OB.NEXTVAL WHERE ROWID=RC.RID;
   END LOOP;

 CLOSE CUR;
  COMMIT;
 END;

As you can see I have three different scripts (I've seperated them with dashed lines.) If I run this the first script runs but the second script, where I want to create a trigger fails saying "Encountered symbol "DECLARE"". If I take the trigger creation script away I get no error and the first and the last scripts run with no problem. What do I have to do to run them all without getting errors?

EDIT: I then realised that the second script should be just like this:

UPDATE ODANBIRM SET OBID=SEQ_OB.NEXTVAL;

So doing this simple thing in a loop is a waste of time and inefficient. I've once heard that one should use as much SQL and as less PL SQL as possible for efficiency. I think it's a good idea.

like image 864
Mikayil Abdullayev Avatar asked Jan 16 '23 16:01

Mikayil Abdullayev


1 Answers

I think it's / on the line immediately following the end of a script. It's needed on ALL end of script lines for PL blocks, including the last. so...

However, do not put it on SQL statements; as it will run it twice (as Benoit points out in comments below!)

ALTER TABLE ODANBIRM 
ADD (OBID NUMBER(10, 0) );
/

CREATE OR REPLACE TRIGGER TR_OB_INC 
BEFORE INSERT ON ODANBIRM
FOR EACH ROW 
BEGIN
  SELECT SEQ_OB.NEXTVAL INTO :NEW.OBID FROM DUAL;
END;
/

DECLARE
CURSOR CUR IS
SELECT ROWID AS RID FROM ODANBIRM;

  RC CUR%ROWTYPE;
BEGIN
  OPEN CUR;

 LOOP
  FETCH CUR INTO RC;

    EXIT WHEN CUR%NOTFOUND;

  UPDATE ODANBIRM SET OBID=SEQ_OB.NEXTVAL WHERE ROWID=RC.RID;
   END LOOP;

 CLOSE CUR;
  COMMIT;
 END;
 /
like image 193
xQbert Avatar answered Jan 31 '23 01:01

xQbert