Download presentation
Presentation is loading. Please wait.
Published byLeona Griffith Modified over 9 years ago
1
Database Management 5. course
2
Today Procedures Functions PL/SQL blocks Triggers
3
Procedures
4
Stored on the server, run on the server – It can be reused – Runs fast (since it is on the server) Two types – Normal program block (PL/SQL) – DB-object (similar sintaxis)
5
Procedures PROCEDURE name [(parameters)] IS local variables BEGIN commands [EXCEPTION exceptions;] END [name];
6
Functions FUNCTION name [(parameters)] RETURN datatype IS local variables BEGIN commands [EXCEPTION exceptions]; END [name];
7
How to call procedurename(parameters); In case of function its return value is used variable:=functionname(parameters);
8
Parameters parametername [IN | OUT | IN OUT] datatype [{:=| DEFAULT}] NULL cannot be given to the parameter Constraint cannot be given to the data type – (id IN NUMBER(4)) -- sintax error – (id IN NUMBER) -- correct
9
Datatype Normal DB datatypes PL/SQL datatypes (http://docs.oracle.com/cd/B19306_01/appdev.102/b1 4261/datatypes.htm) Table.column%TYPE PL/SQL Variable%TYPE Table%ROWTYPE User-defined type: – TYPE rectype IS RECORD(attr 1 type 1,…,attr n type n ); – Var_name rectype; – Var_name.attr 1 :=value;
10
PL/SQL
11
PL/SQL block sintaxis [DECLARE Block_var type] [PROCEDURE name IS…] BEGIN name; [EXCEPTION Block_exc] END; / PROCEDURE name [(parameters)] IS local variables BEGIN commands [EXCEPTION exceptions;] END [name];
12
Example PROCEDURE emp_leaves(dnum NUMBER) IS BEGIN DELETE FROM EMP WHERE empno = dnum; END; BEGIN emp_leaves(7758); END; / dnum: formal parameter 7758: actual parameter
13
SQL command SELECT columns INTO variables FROM table [WHERE condition]; Exactly 1 row is given back! No. of cols=no. of variables
14
Sequence Selection Iteration Sequence Selection Iteration
15
Selection (IF) IF … THEN … END IF; IF … THEN … ELSE … END IF; IF … THEN … [ELSIF … THEN …] ELSE … END IF; No. of ELSIFs is not limited
16
Example PROCEDURE size(a INTEGER) IS b VARCHAR2(40); BEGIN IF a > 999 THEN b := 'four digits or bigger'; ELSIF a > 500 THEN b:= ' bigger than 500'; ELSIF (a > 99) AND (a < 499) THEN b:= 'between 100 and 500' ; ELSIF a > 9 THEN b:= 'two digits' ; ELSE b:= 'one digit'; END IF;... END;
17
Iteration (LOOP) LOOP commands [EXIT;] [EXIT WHEN condition;] END LOOP;
18
Example for LOOP CREATE TABLE order (orderID NUMBER(4), no NUMBER(2), … ); PROCEDURE fill (var_order IN NUMBER) IS var_no NUMBER(2); BEGIN var_no :=1; LOOP INSERT INTO order (orderID, no) VALUES (var_order, var_no); var_no := var_no +1; EXIT WHEN var_no > 5; END LOOP; END;
19
Iteration - FOR FOR variable IN [REVERSE] lower_bound..upper_bound LOOP command; [command;] END LOOP;
20
How it works variable – Initial value := lower_bound (REVERSE: upper_bound) – Increased (REVERSE: decreased) automatically – Until reaches upper_bound (REVERSE: lower_bound) REVERSE: changes direction lower_bound: lowest value of the variable upper_bound: biggest value of the variable
21
Example - FOR CREATE TABLE trial (no NUMBER(3) ); PROCEDURE insert_trial IS BEGIN FOR ind IN 1..5 LOOP INSERT INTO trial (no) VALUES (ind); END LOOP; END;
22
Example - FOR PROCEDURE insert_trial (lower_bound NUMBER, upper_bound NUMBER) IS BEGIN FOR ind IN lower_bound.. upper_bound LOOP INSERT INTO trial (no) VALUES (ind*2); END LOOP; END;
23
Iteration - WHILE WHILE condition LOOP command; [command;] END LOOP; As long as the condition is true.
24
Example - WHILE PROCEDURE insert_order(param_order NUMBER, param_no NUMBER) IS inner_no NUMBER(2):= 1; BEGIN WHILE inner_no <= param_no LOOP INSERT INTO order (orderID, no) VALUES (param_order, inner_no); inner_no := inner_no + 1; END LOOP; END; Insert_order(123, 5); -- inserts 5 items to order no. 123
25
Parameter types
26
IN Only input parameters, the procedure cannot modify its value – Constant – Expression – Not NULL variable
27
Inappropriate usage PROCEDURE owe(account IN INTEGER, amount IN INTEGER) IS min_raise CONSTANT REAL; service CONSTANT REAL; BEGIN … IF amount<min_raise THEN amount:=amount+service; -- sintax error END IF … END
28
Example for default values PROCEDURE new_dept (new_dname CHAR DEFAULT ’MARKETING’, new_loc CHAR DEFAULT ’SAN FRANCISCO’) IS BEGIN INSERT INTO dept VALUES(50, new_dname, new_loc); … END; BEGIN new_dept(); new_dept(’LOGISTICS’); new_dept(’LOGISTICS’,’DENVER’); END;
29
OUT Only output parameters, the procedure cannot read its value (older versions) – Not readable (older versions), writable – Can be called only with variable, cannot be called with expression
30
Inappropriate usage PROCEDURE calculate(id IN INTEGER, premium OUT REAL) IS hired DATE; BEGIN SELECT sal*0.1, hiredate INTO premium, hired FROM emp WHERE empno=id; IF MONTH_BETWEEN(sysdate, hiredate)>60 THEN premium:=premium+5000; -- sintax error (older versions) END IF; END; jut_szam(111, fiz+előleg); -- sintax error
31
IN OUT For reading and writing PROCEDURE calc(id IN INTEGER, premium IN OUT REAL) IS hired DATE; BEGIN SELECT sal*0.1, hiredate INTO premium, hired FROM emp WHERE empno=id; IF MONTH_BETWEEN(sysdate, hiredate)>60 THEN premium:=premium+5000; END IF; END;
32
Conclusions INOUTIN OUT Way of giving to the procedure Not obligatory, default can be used obligatory How it is given to the procedure Gives its value to the procedure Returns with valueGives value, returns with new value BehaviorConstantNot initialized variable Initialized variable Modifiable?Cannot be modifiedNot readable, (older versions) has to be modified Readable, writable What to give to the procedure Constant, variable, expression Just variable
33
Exception DECLARE var_exc EXCEPTION; BEGIN … IF condition THEN RAISE var_exc; EXCEPTION WHEN var_exc THEN dbms_output.put_line(’error’); END;
34
System exceptions Watched by the system automatically – NO_DATA_FOUND: select into didn’t give back rows – TOO_MANY_ROWS: select into gave back several rows – OTHERS: not named exception occured
35
Storage in DB
36
Differences Different sintaxis – AS instead of IS – CREATE has to be used – CREATE OR REPLACE PROCEDURE name… Local variables
37
CREATE OR REPLACE PROCEDURE name (parameter [IN|OUT|IN OUT] type) AS BEGIN commands END; CREATE OR REPLACE FUNCTION name (parameter [IN|OUT|IN OUT] type) AS RETURN return_type BEGIN commands END;
38
DROP PROCEDURE proc_name DROP FUNCTION func_name
39
Triggers
40
Automated action which is executed on DB actions – Table or view is modified – User actions – System actions DB object In PL/SQL, Java, or C language Transparent for the user
41
Trigger events INSERT, UPDATE, DELETE command Some DDL commands (CREATE, ALTER, DROP) Server errors User logins, logoffs DB startups, shut downs
42
What for? Calculate derived values Avoid illegal/inconsistent transactions Protection Define referential integrities Handle complex rules Logging Following users Collecting statistics Cloning data
43
Trigger types Row-level trigger Statement-level trigger BEFORE and AFTER trigger INSTEAD OF trigger System trigger
44
Row-level trigger Run when the data of the table is modified E.g. in case of DELETE command, the trigger is activated for every deleted row.
45
Statement-level trigger Run once irrespectively of the number of the handled rows Run even if no row was modified
46
BEFORE and AFTER triggers Can be both row and statement-level Can be defined only for tables, not for views Valid for the whole schema or database – BEFORE: runs before the connected command – AFTER: runs after the connected command
47
INSTEAD OF trigger Run instead of the connected command Can be defined only on views Just row-level View cannot be modified by DML commands, triggers are used instead.
48
System triggers For giving information about the DB events to the users They ”sign up” for the messages of the database events and other applications. – System events: DB startup, shut down, server error – User events: login, logoff, DML/DDL commands
49
Create trigger CREATE [OR REPLACE] TRIGGER [schema.]name time event ON {DATABASE|[schema].SCHEMA} [WHEN (condition)] command time: BEFORE | AFTER | INSTEAD OF event: – DDL event: for DB or schema – DB event: for DB or schema – DML event: {INSERT |DELETE | UPDATE OF [column, {…}] … ON [schema].table | [schema].view } [REFERENCING {OLD [AS] old | NEW [AS] new | PARENT [AS] parent} … [FOR EACH ROW]
50
DML event INSERT, DELETE, UPDATE – the SQL command, the trigger is connected to UPDATE OF column(s) – run only if the given columns are modified ON: table/schema – the DB object on what the trigger is defined REFERENCING – the OLD and NEW rows are referred here, in case of embedded tables, PARENT table has to be defined FOR EACH ROW – means that it is a row-level trigger (default only at INSTEAD OF)
51
DDL trigger Run on DB or schema event – (ON {DATABASE|[schema].SCHEMA} E.g. ALTER, CREATE, DROP, GRANT, RENAME, REVOKE, TRUNCATE
52
DB event SERVERERROR LOGON: of user application LOGOFF: of user application STARTUP SHUTDOWN SUSPEND: a transaction is suspended because of server error.
53
Example - tables CREATE TABLE Book ( id NUMBER not null,, ISBN VARCHAR2(30) NOT NULL, … Store NUMBER NOT NULL, Free NUMBER NOT NULL, CONSTRAINT book_pk PRIMARY KEY (id), CONSTRAINT book_free CHECK (Free >= 0)) CREATE TABLE Clients ( id NUMBER not null, name VARCHAR2(100) NOT NULL, books NUMBER DEFAULT 0, Max_book NUMBER DEFAULT 10, CONSTRAINT client_pk PRIMARY KEY (id) ) CREATE TABLE Borrow ( Client NUMBER NOT NULL, Book NUMBER NOT NULL, Longer NUMBER DEFAULT 0, dateofloan DATE NOT NULL, … CONSTRAINT borrow_fk1 FOREIGN KEY (Client) REFERENCES Clients(Id), CONSTRAINT borrow_fk2 FOREIGN KEY (book) REFERENCES Book(Id) ) CREATE TABLE Borrow_log ( Book NUMBER NOT NULL, Client NUMBER NOT NULL, Dateofloan DATE NOT NULL, Dateofback DATE NOT NULL )
54
When borrowing a book CREATE OR REPLACE TRIGGER tr_insert_borrow AFTER INSERT ON borrow FOR EACH ROW DECLARE var_client clients%ROWTYPE; BEGIN SELECT * INTO var_client FROM Clients WHERE id = :NEW.client; IF var_client.max_book = var_client.books THEN RAISE_APPLICATION_ERROR(-20010, var_client.name || ' cannot borrow more books.'); END IF; INSERT INTO borrow_log(book,client,dateofloan,dateofback) VALUES (:NEW.book, :NEW.client, :NEW.dateofloan, NULL); BEGIN UPDATE book SET free = free -1 WHERE id = :NEW.book; UPDATE clients SET books = books+1 WHERE id = :NEW.client; EXCEPTION WHEN OTHERS THEN RAISE_APPLICATION_ERROR(- 20020, 'No more free copies of this book.'); END; END tr_insert_borrow; Automated administration of the borrows. Inserting one row to table borrow brings in its train the modification of tables client and book. It is not row-level, since if a book cannot be borrowed, an exception has to be given.
55
When book is returned CREATE OR REPLACE TRIGGER tr_borrow_log AFTER DELETE ON borrow REFERENCING OLD AS oldborrow FOR EACH ROW BEGIN INSERT INTO borrow_log(book,client,dateofloan,dateofb ack) VALUES( :oldborrow.book, :oldborrow.client, :oldborrow.dateofloan, SYSDATE); update clients set books=books-1 where id=:oldborrow.client; update book set free=free+1 where id=:oldborrow.book; END tr_borrow_log;
56
Longer borrow CREATE OR REPLACE TRIGGER tr_borrow_long BEFORE INSERT OR UPDATE ON borrow FOR EACH ROW WHEN (NEW.longer > 2 OR NEW.longer < 0) BEGIN RAISE_APPLICATION_ERROR(- 20005, 'No more prolong'); END tr_borrow_long; After WHEN : is not needed before placeholders (OLD, NEW, PARENT) Check or assertion can be used also
57
Do not modify borrow_log CREATE OR REPLACE TRIGGER tr_borrow_log_del_upd BEFORE DELETE OR UPDATE ON borrow_log BEGIN RAISE_APPLICATION_ERROR (-20100, 'Permission denied.'); END tr_borrow_log_del_upd; Statement-level trigger there is no FOR EACH ROW
58
Example 2 CREATE TABLE num_table(a NUMBER); CREATE OR REPLACE TRIGGER tr_double BEFORE INSERT ON num_table FOR EACH ROW BEGIN :NEW.a := :NEW.a * 2; END tr_double; INSERT INTO num_table VALUES(5); SELECT * FROM num_table; Double the values before insertion :NEW can be modified
59
CREATE OR REPLACE TRIGGER tr_book_id BEFORE UPDATE OF id ON book FOR EACH ROW BEGIN UPDATE borrow SET book = :NEW.id WHERE book = :OLD.id; END tr_book_id; Force integrity constraint: book in table borrow is foreign key Before modifying book id we modify the values in table borrow
60
CREATE OR REPLACE TRIGGER tr_client_book_mod INSTEAD OF UPDATE ON client_book FOR EACH ROW BEGIN IF :NEW.client <> :OLD.client THEN UPDATE clients SET name = :NEW.client WHERE id = :OLD.client_id; END IF; IF :NEW.book <> :OLD.book THEN UPDATE book SET title = :NEW.book WHERE id = :OLD.book_id; END IF; END tr_client_book_mod; Modify the client’s name or the book’s title through view client_book: CREATE OR REPLACE VIEW client_book AS SELECT clients.id AS client_id, clients.name AS client, book.id AS book_id, book.title AS book FROM borrow,book,clients WHERE borrow.book=book.id AND clients.id=borrow.client;
61
Delete a trigger DROP TRIGGER table.trigger
62
Thank you for your attention!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.