Cursors • To manipulate the information within SQL statement by means of assigning a name to a ‘select statement’ is known as ‘cursor’ • Used for processing individual rows returned as a result for a query. • Cursors are special work area in sql. - The work area contains specific set of rows that are selected by select statements. - These work areas are referred by the name of cursors. • A cursor usually stores a set of rows that are selected by select statements and it is used to manipulate those records by fetching them one by one. • Cursor program includes four sub parts namely, – Cursor declaration – Opening a Cursor – Fetching – Closing a Cursor Cursor Declaration: A cursor variable is declared in the declaration part of PL/SQL block. Syntax: Cursor <cursor_name> is <select statement> Opening a Cursor: Before using a cursor it should be opened. The open statement should be given in the BEGIN – END construct. A cursor when opened, will point to the first row by default. Syntax: Open <cursor_name> Fetching: The set of rows held by a cursor can be fetched (read) row by row. A single fetch statement moves the cursor pointer by one row. Syntax:
Fetch <cursor_name> into <variable_list>
Closing a Cursor: After processing all the records , the
cursor can be closed. Syntax: Close <cursor_name> Example declare row doctors %rowtype; cursor d is select * from doctors where rank='sr.surgeon'; begin open d; loop fetch d into row; exit when d %notfound; insert into docinfo values(row.dnum,row.dname,row.phno); end loop; close d; end; / Example declare row doctors %rowtype; cursor c is select * from doctors where rank='surgeon'; begin open c; loop fetch c into row; exit when c %notfound; update doctors set rank='sr.surgeon'; end loop; close c; end; / Example declare row doctors %rowtype; cursor c is select * from doctors where rank='surgeon‘ for update of rank; begin open c; loop fetch c into row; exit when c %notfound; update doctors set rank='sr.surgeon‘ where current of c; end loop; close c; end; / Procedures A stored procedure is a subroutine available to applications that access a relational database system. Typical use for stored procedures include data validation (integrated into the database) or access control mechanisms. CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter [,parameter]) ] IS [declaration_section] BEGIN executable_section [EXCEPTION exception_section] END [procedure_name]; Types of parameters Types of parameters : • IN - The parameter can be referenced by the procedure or function. The value of the parameter can not be overwritten by the procedure or function. • OUT - The parameter can not be referenced by the procedure or function, but the value of the parameter can be overwritten by the procedure or function. • IN OUT - The parameter can be referenced by the procedure or function and the value of the parameter can be overwritten by the procedure or function. Procedures create or replace procedure p is row patient %rowtype; cursor c is select * from patient where rank='SR'; Begin open c; Loop fetch c into row; exit when c %notfound; insert into sr(pid, pname) values(row.pid,row.pname); commit; end loop; close c; end;
EXECUTE [or EXEC] procedure_name
• Write a procedure to store the studentno, name, class name, fid, fname and dept id in a new table for meet_at Tuesday • Write a procedure to give incentive to all the doctors whose rank is surgeon. If no such doctor found the give appropriate message. Procedure Example create or replace procedure p ( rank_in IN varchar2)is row patient %rowtype; cursor c is select * from patient where rank=rank_in; Begin open c; Loop fetch c into row; exit when c %notfound; insert into sr(pid, pname) values(row.pid,row.pname); commit; end loop; close c; end; • Using IN and OUT parameter: Let’s create a procedure which gets the name of the employee when the employee id passed. 1> CREATE OR REPLACE PROCEDURE emp_name (id IN NUMBER, emp_name OUT NUMBER) 2> IS 3> BEGIN 4> SELECT first_name INTO emp_name 5> FROM emp_tbl WHERE empID = id; 6> END; 7> / We can call the procedure ‘emp_name’ in this way from a PL/SQL Block. 1> DECLARE 2> empName varchar(20); 3> CURSOR id_cur SELECT id FROM emp_ids; 4> BEGIN 5> FOR emp_rec in id_cur 6> LOOP 7> emp_name(emp_rec.id, empName); 8> dbms_output.putline('The employee ' || empName || ' has id ' || emp-rec.id); 9> END LOOP; 10> END; Triggers • A trigger is a statement that is executed automatically by the system as a side effect of a modification to the database. • To design a trigger mechanism, we must: – Specify the conditions under which the trigger is to be executed. • Events- cause the trigger to be checked • Condition – must be satisfied for trigger execution to proceed – Specify the actions to be taken when the trigger executes. -> event-condition- action model • Db stores the triggers like regular data; persistent and accessible to all db operations. • Useful mech. for alerting humans or for starting certain tasks automatically when certain conditions are met. Trigger Example • Suppose that instead of allowing negative account balances, the bank deals with overdrafts by – setting the account balance to zero – creating a loan in the amount of the overdraft – giving this loan a loan number identical to the account number of the overdrawn account
• The condition for executing the trigger is an
update to the account relation that results in a negative balance value. When not to use triggers • Trigger should be written carefully, a trigger error detected at run time causes the failure of inert/delete/update st. that set off the trigger. • Lead to an infinite chain of triggering (insert trigger). • Called as rules, active rules. Oracle/PLSQL Topics: Creating Triggers • Insert Triggers: • BEFORE INSERT Trigger • AFTER INSERT Trigger • Update Triggers: • BEFORE UPDATE Trigger • AFTER UPDATE Trigger • Delete Triggers: • BEFORE DELETE Trigger • AFTER DELETE Trigger • Drop Triggers: • Drop a Trigger • Disable/Enable Triggers: • Disable a Trigger • Disable all Triggers on a table • Enable a Trigger • Enable all Triggers on a table BEFORE INSERT Trigger A BEFORE INSERT Trigger means that Oracle will fire this trigger before the INSERT operation is executed. The syntax for an BEFORE INSERT Trigger is: CREATE or REPLACE TRIGGER trigger_name BEFORE INSERT ON table_name [ FOR EACH ROW ] DECLARE -- variable declarations BEGIN -- trigger code EXCEPTION WHEN ... -- exception handling END; trigger_name is the name of the trigger to create. Restrictions: You can not create a BEFORE trigger on a view. You can update the :NEW values. You can not update the :OLD values. Triggers
• The syntax for a dropping a Trigger is:
DROP TRIGGER trigger_name; • The syntax for a disabling a Trigger is: ALTER TRIGGER trigger_name DISABLE; • The syntax for a disabling all Triggers on a table is: ALTER TABLE table_name DISABLE ALL TRIGGERS; • The syntax for a enabling a Trigger is: ALTER TRIGGER trigger_name ENABLE; • The syntax for a enabling all Triggers on a table is: ALTER TABLE table_name ENABLE ALL TRIGGERS; Triggers create or replace trigger a after insert on patients for each row begin if (:new.page<20) then raise_application_error(20000, 'enter correct age'); else insert into patients(pnum,pname,page) values(:new.pnum,:new.pname,:new.page); end if; end; / Triggers create or replace trigger a before update or insert on patients for each row declare age1 number(10); begin select page into age1 from patients; if age1<20 and age1>30 then dbms_output.put_line('enter correct age'); end if; end; / Triggers create or replace trigger a after insert or before update on patients for each row begin if (:new.page<20) then raise_application_error(20000, 'enter correct age'); else insert into patients(pnum,pname,page) values(:new.pnum,:new.pname,:new.page); end if; end; /