0% found this document useful (0 votes)
19 views39 pages

Book Scan - Chapter II RDBMS

Chapter II

Uploaded by

ashwini bhosale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
19 views39 pages

Book Scan - Chapter II RDBMS

Chapter II

Uploaded by

ashwini bhosale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 39
RDBMS (B.C.A.- I!) 2.54 2.4.4 User Defined Exceptions There are two methods of defining exception by user. (a) RAISE statement (b) RAISE_APPLICATION_ERROR statement. PUSa RAISE Statement Ifyou explicitly need to raise an error then RAISE statement is used and yo, have to declared an exception variable in declared section. For example : | DECLARE TEMP_Sal NUMBER (10,2) ; NEGATIVE_SAL EXCEPTION; BEGIN SELECT sal INTO TEMP_sal From emp | WHERE empno=7698; | } | IF TEMP_sal < 0 THEN Raise NEGATIVE_SAL; ELSE UPDATE emp SET sal = 5000 WHERE empno=7698; END IF; COMMIT ; EXCEPTION WHEN NO_DATA_FOUND THEN Dbms_output .put_line(‘Record NOT FOUND’); WHEN NEGATIVE_SAL THEN Dbms_output .put_line(‘Salary is negative’); END; If the above example find row with an Sal less than 0 then PL/SQL raise user_defined Negative_sal exception. RAISE_APPLICTAION_ERROR Statement The RAISE_APPLICATION_ERROR takes two input parameters : the ert number and error message. The error number must be between -20001 to” 20999. You can call RAISE_APPLICATION_ERROR from within procedure functions, packages and triggers. ~ pas (0A. - Mi) 2.55 PUSQL For examples : DECLARE TEMP_Sal NUMBER (10,2) ; BEGIN SELECT sal INTO TEMP sal From emp . WHERE empno=7698; UPDATE emp SET sal = TEMP_sal ¥1.5 WHERE empno=7698; COMMIT; EXCEPTION WHEN NO_DATA_FOUND THEN RAISE_APPLICATION_ERROR (-20100, ‘Record NOT FOUND’); END Note that in this case exception variable declaration is not required. 2. DECLARE TEMP_sal NUMBER (10, 2); BEGIN SELECT sal INTO TEMP_sal from emp WHERE empno = 7698; If temp_sal < 0 then Raise_application_error (- 20010, ‘Salary is negative'); else UPDATE emp SET sal = 5000 WHERE empno = 7698; end if; EXCEPTION WHEN NO_DATA. FOUND THEN DBMS_OUTPUT.PUT_LINE('Record not found'); end; Program 2.17: Accept empno and check whether it is present in emp table or not. Declare v_no emp.empno%type; v_empno emp.empno%type; Begin V_empno:=&v_empno; select empno into v_no from emp ROBMS (B.C.A. - Il) 2.56 PUsy | where empno=v_empno; if v_no=v_empno then dbms_output .put_line ('Empno exists'); end if; When no_data_found then dbms_output .put_line('Empno does not exists'); End; Outpu: SQL> / Enter value for v_empno: 7768 old 5: v_empno:=&v_empno; new 5: v_empno:=7768; Empno does not exists SQL> / | Enter value for v_empno: 7698 old 5: v_empno:=&v_empno; new 5: v_empno:=7698; Empno exists Program 2.18 : Print name of emp getting second max salary. v_name emp.ename%type; Begin i | | | | | Declare select e2.ename into v_name from emp el, emp e2 where e1.sal>e2.sal; | dbms_output..put_line(v_name || ‘is getting second max salary')i | Exception When too_miny_rows then dbms_output.put_line('More than one Empno getting secom | max salary'): | End; | Outpu SQL> / | More than one Empno getting second max salary. | Program 2.19 : Accept empno and check whether comm is null or not. If comm is null raise an exception otherwise display comm. Declare v_comm emp.commstype; v_empno emp.empno%type; 5 8. oem 2.87 Pusat check_comm exceptio, pegin v_empno:=&V_empno; select comm into v_comm from emp where empno=v_empno;' if v_comm is NULL then xaise check_comm; else dbms_output -put_line( ‘comm = +] |y comm) ; end if; = Exception . When no_data_found then i i dbms_output .put_line('Empno does not exists'); When’ check_comm then dbms_output .put_line('Empno getting null comm') ; End; Output : SQL> / Enter value for v_empno: 7566 old 6: v_empno:=&v_empno; new 6: v_empno:= 7566; Empno getting null comm SQL> / Enter value for v_empno: 7521 old 6: v_empno:=&v_empno; new 6: v_empno:=7521; comm = 500 Exception Handling in PL/SQL Syntax for exception handling in PL/SQL on given below : EXCEPTION WHEN THEN / Enter value for v_empno: 7566 old 6: v_empno:=&v_empno; new 6: v_empno:= 7566; Empno getting null comm SQL> / Enter value for v_empno: 7521 old 6: v_empno:=&v_empno; new 6: v_empno:=7521; comm = 500 Exception Handling in PL/SQL Syntax for exception handling in PL/SQL on given below : EXCEPTION WHEN THEN exception BEGIN ; IF THEN ROBMS (B.C.A. = Il) 2.58 Pus, 1. | DUP_VAL_ON_INDEX | Raised when an insert or update attempts to create two rows with duplicate values in columns constrained by a unique index. 2. | PROGRAM_ERROR _ | Raised when PL/SQL has an internal problem. 3.|NO DATA FOUND _| Raised when select statement returns zero rows. 4, | LOGIN-DEMIED Raised when an invalid username/passward was used to log onto oracle. (i) Displaying user messages on VDU screen. Dbms_output.put_line (‘message’); DBMS-output : This package includes number of procedures and functions which can be used to display message and stored information in buffer. Put-line : Puts a piece of information in the package buffer and to display message. To display message, the SERVEOUTPUT should be set to N. Syntax : SET SERVEOUTPUT (ON/OFF) (ii) Comments 1) Single comment line begins with double hyphen (--). 2) Multiline comment begin with a/* and followed by */. Syntax: /* Comment line */ TCC_Many_Rows Raised when a select statement returns more then one row. Cursor_Already_open _ Raised when SQL cursor is open.& User-defined Exceptions User defined error conditions must be declared in the declaration part of any PL/SQL block. In the executable port, a check for the condition that needs special attention is mole. If the condition exists, the call to the user defined exception is made using RAISE st. Syntax : DECLARE exception BEGIN ; IF THEN \ poems (0-8) 2.69 RAISE END IF; ; exception When Then {user defined action ‘to be 7% END; ‘aken’ }; 9.5 FUNCTIONS A function contain a PL/SQL block to perform specific task, It can read a list of values but it will explicitly return a single value which is normally assigned to a variable. 2.5.1 What is a Function ? A function is a named PL/SQL Block which is similar to a procedure. The major difference between a procedure and a function is, a function must always return a value, but a procedure may or may not return a value 2.5.2 How to Execute a Function? A function can be executed in the following ways. 1, Since, a function returns a value we can assign it to a variable. employee_name employer_details_func; If ‘employee_name’ is of datatype varchar we can store the name of the employee by assigning the return type of the function to it. 2, Asa part of a SELECT statement, SELECT employer_details_func FROM dual; 3. Ina PL/SQL Statements like, dbms_output .put_line (employer_details_func) ; 2.5.3 Creating a Function Syntax : CREATE [OR REPLACE] FUNCTION function _name [(argument [in/out/in out] datatype {,argument [in/out/in out) datatype RETURN datatype {1s / as} [variable declaration] {PL/SQL block}; The syntax of function is same as that of procedure only difference is RETURN datatype has to specify since function must return a value. Wy) ROBMS (B.C.A.- il) eee i USO. Program 2.20: Pass empno as a parameter to function and function wij return salary. CREATE OR REPLACE FUNCTION myfuncl (£_no IN number) RETURN number 1s V_sal emp. sal $TYPE; Begin Select sal into v_sal From emp Where emp_no=f_no; If SQL&FOUND then RETURN (v_sal) ; Else RETURN 0; End if; END myfuncl; 13.5.4 Deleting a Function To delete a function DROP FUNCTION command is used. Syntax : DROP FUNCTION function_name; For example : DROP FUNCTION myfuncl; PROGRAMS Program 1 : Pass a no. to a function and check whether it is divisible by S or not. create or replace function fl (£_no in number) return number as Begin if (mod(f£_no,5)=0) then Téturn 1;, else return 0; end if; End £1; ic Function can be executed using select statement by calling Program as follows ; SQL> select £1 (10) from dual; ) Pl (10) 2. < PUSQL dbms_output put_line(no | | ' is divisible by 5'); else L i aons_output .put_line(no || + is not divisible by 5"); end i End; output + sQh> / Enter value for no: 30 new 5: no 30 is divisible by 5 SQL> / Enter value for no: 12 old 5: new 5: no: 12 is not divisible by 5 Program 2 : Pass two string to a function and print which string is largest. create or replace function £2 (str1 in varchar2, str2 in varchar2) return varchar2 as Ll number; 12 number; Begin Lirslength (str); L2:=length(str2) ; if (LlsL2) then return 'First string is largest @lse if(L2 >Li ) then return 'Second string is largest'; else N. \ ROBMS(6.C.A. - Il) 2.62 return 'Both are equal; end if; end if; End £2; / Output : SQL> select £2('smita','chavan') from dual; F2('SMITA', 'CHAVAN') Second string is largest SQL> select f2('hello','hi') from dual; F2('HELLO', 'HI') First string is largest SQL> select f2('smita','swati') from dual; F2 ('SMITA', 'SWATI') Both are equal AOBMS (8.C.A.- Il) 2.6 PROCEDURE E iccaacerincetnct ad Procedures are simply procedure is completely pp 4 named PL/SQL block, that executes certain task. A ortable among platforms in which Oracle is executed. 2.6.1 Creating a Procedure A procedure is created using CREATE PROCEDURE command. Syntax CREATE [OR REPLACE] PROCEDURE procedure _name ((argument [in/out/in out) datatype [,argument [in/out/in out] i {is / as} ivariable declaration] {PL/SQL block}; [Note : Square brakets | ] indicate optional part. J CREATE PROCEDURE procedure_name will create a new procedure with the given procedure_name. OR REPLACE is an optional clause. It is used to change the definition of an existing procedure. If the procedure accept arguments specify argument details as Argument_name IN / OUT / IN OUT datatype Argument_name indicate Variable_name IN indicate the variable is passed by the calling program to procedure. OUT indicate that the variable pass value from procedure to calling program. IN OUT indicate that the variable can pass values both in and out of a procedure. Datatype specify any PL/SQL datatype. Program 2.21 : Pass empno as an argument to procedure and modify salary of that emp. CREATE OR REPLACE PROCEDURE myprocl (p_no IN number) /* argument */ Is” ' v_sal number (10,2); BEGIN Select sal into v_sal From emp Wheré empno=p_no; » RDBMS (B.C.A. - IN) 2.72 PUsa If v_sal > 1000 then Update emp Set sal = Update emp Set sal = 5000 Where empno=p_no; End if; EXCEPTION WHEN NO_DATA_FOUND THEN Dbms_output .put_line(‘Emp_no doesn’t exists’); END myprocl; 2.6.2 Executing a Procedure To execute the stored procedure simply call it by name in EXECUTE command as, SQL> execute myprocl (7768) ; This will execute myprocl with the value 7768. The second method of calling the procedure is Write the following code in an editor. Declare C_empno number; Begin Myprocl (&c_empno) ; End; ii z Execute it as SQL >/ In this case the value of variable c_empno is accepted from user and then it is pss to myprocl procedure. To see the effect of this procedure use command SQL>select » from emp Program 2.22 : Pass a empno as argument to procedure and procedure will pass job to the calling program. CREATE OR REPLACE PROCEDURE myproc2 (p_no IN number, p_job' OUT emp.job%TYPE) /* arguments */ v_job emp. job%TYPE; RDBMS (B.C.A. - Ill) 2.72 PUsq. Tf v_sal > 1000 then Update emp Set sal = v_sal*1.75 Where empno=p_no; Else Update emp Set sal = 5000 Where empno=p_no; End if; EXCEPTION WHEN NO_DATA_FOUND THEN Dbms_output.put_line(‘Emp_no doesn’t exists’); END myproc 2.6.2 Executing a Procedure To execute the stored procedure simply call it by name in EXECUTE command as, SQL> execute myprocl (7768) ; This will execute myproc! with the value 7768. The second method of calling the procedure is Write the following code in an editor. Declare C_empno number; Begin Myprocl (&c_empno) ; End; 7 A Execute it as SQL >/ In this case the value of variable c_empno is accepted from user and then it is pa'ss to myprocl procedure. To see the effect of this procedure use command SQL>select » from emp Program 2.22 : Pass a empno as argument to procedure and procedure will pass job to the calling program. CREATE OR REPLACE PROCEDURE myproc2 (p_no IN number, p_job’ OUT emp.job%TYPE) »/* arguments */ Is v_job emp. job’ TYPE; ys cM) 279 PUSOL & peGIN . select JOB into v_job From emp where empno=p_no; p_job:=v_job; picePTION wHEN NO_LDATA_FOUND THEN P_job:='No’; sno nyproc: galling procedure myproc2? using following code peclare M4 Pro cempno number ;~ ————— ¢_job wey foor Grows zegin Myproc2 (&c_empno, c_job) ; _ ¥ If c_job='NO’ then a Dbms_output .put_line(*Emp_no doesn’t exists’); Else Dbms_output.put_line(‘Job of emp. Is ‘ || ¢_job); End if; End; / Execute this code using Salo / CEES 2.73 Pusat, into v_job p_job:='NO'; | gxo nyproc? | Gling procedure aaa using following code peclare 4 Proc Gempno| number ;~————— Eyed _emp-JOb¥TYPE; gay foo, BUNS | begin nyproc2 (&c_empno, ¢_job) ; : If c_job=’NO’ then ws Dbms_output .put_line(‘Emp_no doesn’t exists’); Else Dbms_output .put_line(‘Job of emp. Is‘ || ¢ Job): End iff and; / zrecute this code using soL> / Program 2.23; Pass salary to procedure and procedure will pass no. of oe erate ae see aee / 2.6.3 Deleting a procedure To delete a procedure DROP PROCEDURE command is used. Syntax : DROP PROCEDURE procedure_name; For example : DROP PROCEDURE myprocl; PRA: 2.7 CURSORS Whenever, a SQL statement is issued the Database server opens an area of memory is called Private SQL area in which the command is processed and executed. An identifier for this area is called a cursor. When PL/SQL block uses a select command that returns more than one row, Oracle displays an error message and invokes the TOO_MANY_ROWS exception. To resolve this problem, Oracle uses a mechanism called cursor. There are two types of cursors. 2. Explicit cursors. PL/SQL provides some attributes which allows to evaluate what happened when the cursor was last used. You can use these attributes in PL/SQL opus 80-8. Ae ts like functio PuSOL temen! but you cannot use the: i the SQL CUrsor attributes are - m within SQL statements. %ROWCOUNT : 1 The number of rows Processed by a SQL statement. 2, FOUND : TRUE if at least one row was processed 3, *NOTFOUND : TRUE if no rows were processed 4, %ISOPEN : TRUE if cursor is 0) pen or FALSE if cursor has not been opened or has been closed. Only used with explicit cursors. 9.7.1 What are Cursors? Ay cursor is‘a té A Sstement feat work area created in ‘the system memory when. a. set ae acne ited. 'A-cursor contains information on a select statement an 3 ta accessed by it. This t i nd the . ta accesse ; e the data retrieved s temporary work area is used. to store from the database, and manipulate this data. A cursor-can hold more_than.one row, but can c rows the cursor holds is called th 2.7.2 Definition A cursor is a temporary work area used to store the data retrieved from the ee and manipulate this data. e OR A cursor is a temporary work area created by system memory when SQL/PL/SQL statements are executed. 2.7.3 Declaring a Cursor Cursors are defined within a DECLARE section of a PL/SQL block with DECLARE command. Syntax : cursor cursor_name [(parameters)] [RETURN return_type] IS SELECT query. The cursor is defined by the CURSOR keyword followed by the cursor identifier (Cursor_name) and then the SELECT statement. Parameter and return are optional part. When parameters are passed to cursor it is called as parameterized cursor. For example :' DECLARE CURSOR c_deptno IS SELECT ename,sal,deptno FROM EMP; 2.7.4 Opening a Cursor Cursors are opened with the OPEN statement, this populates the cursor with data. Syntax : OPEN Cursor_name [parameters] ; ROBMS (8.C.A. - wy 2.82 Py For example : DECLARE CURSOR c_deptno 1S SELECT ename,sal,deptno 7 FROM EMP; Begin Open c_deptno; End; , ; Parameters is an optional part. It is used in parameterized cursor, ‘Accessing the cursor rows To access the rows of data within the cursor the FETCH statement is Used. For example : DECLARE CURSOR c_deptno IS SELECT ename,sal,deptno FROM EMP; V_name emp.ename%type; v_sal emp.salstype; v_deptno emp.deptno%type; Begin Open c_deptno; FETCH c_deptno INTO v_name,v_sal,v_deptno; Dbms_output.put_line(V_NAME [|’ ‘|[V_deptno||’ ‘||V_saL); End; SQL > / SMITH 800 20 The FETCH statement reads the column values for the current cursor row and puts them into the specified variables. This can be as an equivalent to the SELECT INTO command. The cursor pointer is updated to point at the next row. If the cursor has no more rows the variables will be set to null on the first FETCH attempt, subsequent FETCH attempts will raise an exception. To process all the rows within a cursor use a FETCH command in a loop and check the cursor NOTFOUND attribute to see if we successfully fetched a row or not as follows : DECLARE CURSOR c_deptno Is SELECT ename, sal,deptno FROM EMP; V_name emp.ename%type ; v-sal emp.sal%type; v_deptno emp.deptno%type; Begin Open c_deptno; Loop ie ¢_deptno INTO v_name,v_sal,v_deptno; Exit when c_deptno%NOTFOUND; Dbms_output.put_line(V_NAME ||‘*||V_deptno] |’ *||V_SAL)i End loop; End; Pl RDBMS (8.C.A. - Ill) eee sy For example : DECLARE me, Sal, deptno © IS SELECT ename, CURSOR — c_deptn SE CuIEMPy Begin Open c_deptno; End; ; , 4 Parameters is an optional part. It is used in parameterized curso) Accessing the cursor rows To access the rows of data within the cursor the FETCH statement is Used For example : fem cueeen ¢_deptno Is SELECT ename,sal,deptno ~ FROM EMP; V_name emp. ename%type; v_sal emp.sal%type; v_deptno emp.deptno%type; Begin Open c_deptno; FETCH c_deptno INTO v_name,v_sal,v_deptno; Dbms_output.put_line(V_NAME ||’ ‘|[V_deptno||‘ *||V_SaL); End; SQL > / SMITH 800 20 The FETCH statement reads the column values for the current cursor row and puts them into the specified variables. This can be as an equivalent to the SELECT INTO command. The cursor pointer is updated to point at the next row. If the cursor has no more rows the variables will be set to null on the first FETCH attempt, subsequent FETCH attempts will raise an exception. ny To process all the rows within a cursor use a FETCH command in a loop and | check the cursor NOTFOUND attribute to see if we successfully fetched a row or not as follows : DECLARE CURSOR c_deptno IS SELECT ename,sal,deptno FROM EMP; V_name emp.ename%type; vesal emp.sal%type; v_deptno emp. deptnostype; Begin Open c_deptno; Loop FETCH ¢_deptno INTO v_name,v_sal,v_deptno; Exit when c_deptno%NOTFOUND;~ 7 Dbms_output.put_line (V_NAME II End loop; = End; ‘*|[V_deptno| |**| |V_SAL); CALM) es ee ¢ PUsOL 9.7.5 Closing a Cursor a e CLOSE statement rele: pyeur ‘thin i 5 sent amen eaain te refresh thoastene et and any rows within it, youcam, Syme LOSE Cursor_name; For example : Close c_deptno; Close c_deptno; End; ising Cursor Fo: 00. {in the cursor FOR loop, the result of SELECT query are used to determine the number of times the loop is executed. In a Cursor FOR loop, the opening, fetching and closing of cursors is performed implicitly. When you use it, Oracle automatically declares a variable with the same name as that is used as a counter in the FOR command. Just precede the name of the selected field with the name of this variable to access its contents. For example : DECLARE, CURSOR c_deptno IS _ SELECT ename,sal,deptno K emp firotskype FROM EMP; Begin f *3e For x in c_deptno Loop’ Dbms_output.put_line(x.ename ||’ ‘||x.deptno]|’ *||x.SAL); End 100; End; In above example a Cursor For loop is used, there is no open and fetch command. For x in c_deptno implicitly opens the c_deptno cursor and fetches a value into the x variable. Note that x is not explicitly declared in the block. Hen no more records are in the cursor, the loop is exited and cursor is poet There is no need to check the cursor %NOTFOUND attribute-that is ‘automated via the cursor FOR loop. And also there is no need of close command. 2.7.6 Cursor Variables A cursor variable is a reference type. It can refer to different storage locations as the program runs. To use cursor variable, first the variable has to be declared. And the storage has to allocated. It.is then opened, fetched and closed similar to a static cursor. Syntax : TYPE type_name IS REP CURSOR [RETURN roturn_typel; wre Se 0) 2.03 ¢ PUSaL « : \ The CLOSE statement releases the cursor and any rows within it, youcam open the cursor again to refresh the data in it = tax ¢ sym CLOSE Cursor_name; example : Fo Close c_deptno; close ¢_deptno; End; \(sing Cursor For.... Loo; {in the cursor FOR loop, the result of SELECT query are used to determine the number of timiés the loop is executed. In a Cursor FOR loop, the opening, fetching and closing of cursors is performed implicitly. When you use it, Oracle automatically declares a variable with the same name as that is used as a counter in the FOR command. Just precede the name of the selected field with the name of this variable to access its contents. For example : DECLARE CURSOR c_deptno Is SELECT ename,sal,deptno % emp iirerahype FROM EMP: sus cA 3.15 Closing a Cursor Begin For x in c_deptno 7 wr Dbms_output .put_line(x.ename ||‘ *||x.deptno||‘ *||x.SAL); End loop; End; In above example a Cursor For loop is used, there is no open and fetch command. For x in c_deptno implicitly opens the c_deptno cursor and fetches a value into the x variable. Note that x is not explicitly declared in the block. hen no more records are in the cursor, the loop is exited and cursor is poe |. There is no need to check the cursor %NOTFOUND attribute-that is automated via the cursor FOR loop. And also there is no need of close command. 2.7.6 Cursor Variables A cursor variable is a reference type. It can refer to different storage locations as the program runs. To use cursor variable, first the variable has to be declared. And the storage has to allocated. It is then opened, fetched and closed similar to a static cursor. Syntax : TYPE type_name IS REP CURSOR [RETURN return_type]; = ene goous 0.8 tI) 2 2.7.5 Closing a Cursor the CLOSE statement releases the pen the cursor again to refresh the d tax t syat" CLOSE Cursor_name; For example : Close c_deptno; close c_deptno; End; \-(Using Cursor Fo: Loo} {in the cursor FOR loop, the result of SELECT query are used to determine the number of times the loop is executed. In a Cursor FOR loop, the opening, fetching and closing of cursors is performed implicitly. When you use it, Oracle automatically declares a variable with the same name as that is used as a counter in the FOR command. Just precede the name of the selected field with the name of this variable to access its contents. cursor and any rows within it, you\cdm, ata in it, = For example = DECLARE CURSOR c_deptno IS SELECT ename,sal,deptno ¥cemp iy zeus FROM EMP; Begin f Fyre For x in c_deptno oop’ Lars rescue seers GO sas Il’ ‘| |x-deptno||’ *||x.SAL); End loop; End; In above example a Cursor For loop is used, there is no open and fetch command. For x in c_deptno implicitly opens the c_deptno cursor and fetches a value into the x variable. Note that x is not explicitly declared in the block. en no more records are in the cursor, the loop is exited and cursor is sed. There is no need to check the cursor %NOTFOUND attribute-that is ‘automated via the cursor FOR loop. And also there is no need of close command. 2.7.6 Cursor Variables A cursor variable is a reference type. It can refer to different storage locations as the program runs. To use cursor variable, first the variable has to be declared. And the storage has to allocated. It.is then opened, fetched and Closed similar to a static cursor. Syntax : TYPE type_name IS REP CURSOR [RETURN return_type] ; ROBMS (B.C.A. - tl) 2.64 Psy Where type_name is the name of new reference type and return.type js cl record type. DECLARE “+. Defination using Rowtype TYPE student_R is REF CURSOR RETURN students % ROWTYPE; Define a new record type TYPE Student_Rec IS RECORD { fname students. f_name%TYPE, iname students_1_name%TYPE) ; variable of new type Namerec Student _REC; BEGIN END; Constrained and Unconstrained Cursor variables 1, Constrained Variables When the cursor variables are declared for a specific return type only, then these variables called constrained variables. When these variables are later opened, it must be opened for a query whose ‘select’ list matches the return type of the cursor. Otherwise predefined exception ROWTYPE_MISMATCH is raised. 2, Unconstrained Variables : An unconstrained cursor variable does not have a RETURN clause. When this variable is later opened, it can be for any query. Example of unconstrained variable TYPE Stock_cur-price IS REF CURSOR; a variable of that type v_cursor var stock_cur_price; BEGIN poems (8.0.8. oa . pusoL 3, Opening a cursor variable fora query : syntax : OPEN cursor_variable FOR select_statement; Where cursor_variable is a previously declared cursor variable and select_st. js the desired query. If the cursor variable is constrained, the select statement must match the return type of the cursor. Otherwise it raised error. OPEN Student_R FOR Select * from students; 4, Closing the Cursor Variables : The CLOSE statment closes or deactivates the previously opened cursor and makes the active set undefined. After the cursor is closed, user cannot perform any operation on it. CLOSE Cursor_name; where cursor_name is previously opened cursor name. It does not necessary free the storage for the cursor variable itself. It is fixed when the variable goes out of scope. 5. Restrictions on Using cursor variables : Cursor variable are a powerful feature of allowing different kinds of data to be returned in same variable. But, there are a number of restrictions with their use, 1. PL/SQL collections (index-by-tables, Nested tables and V arrays) cannot store cursor variables. Similarly database tables and views can not store REF CURSOR columns. 2. The query associated with a cursor-variable in the OPEN-FOR statement can not be FOR UPDATE. 3. Remote subprograms cannot return the value of a cursor variable. They can be passed between client and server side PL/SQL (from oracle forms clients), but not between two servers. 4. You cannot use cursor variables with dynamic SQL in pro*c 2.7.7 Implicit Cursor When the executable part of a PL/SQL block issues a SQL command, PL/SQL creates an implicit cursor which has the identifier SQL. PL/SQL internally manages this cursor. Program 2.24 : Print no. of rows deleted from emp. DECLARE ROW_DEL_NO NUMBER; BEGIN DELETE FROM EMP; ROW_DEL_NO := SQL%ROWCOUNT; DBMS_OUTPUT.PUT_LINE('No. of rows deleted are :'|| RDBMS (B.C.A, IN) 2.06 2 PUso ROW_DEL_No) ; END; / SQL> / No. of rows deleted are : 14 PL/SQL procedure successully completed Program 2.25 : Accept empno and print it’s details(using cursor). DECLARE v_No EMP. EMPNOSTYPE : =&V_NO; V_NAME EMP. ENAMESTYPE; V_JOB EMP. JOBSTYPE; V_SAL EMP. SAL&TYPE; BEGIN SELECT ename,job,sal INTO V_NAME,V_JOB,V_SAL FROM emp WHERE empno=V_Nt IF SQLSFOUND THEN /* SQL&FOUND is true if empno=v_no */ Dbms_output.put_line(V_NAME ||’ *||V_goB/|‘ ‘||V_SAL); Exception when no_data_found then dbms_output.put_line ('Empno does not exists'); End; SQL > / Enter value for v_no : 34 Old 2 : v_no emp.empno%typ: New 2 : v_no emp.empno%typ. Empno does not exists PL/SQL rpocedure successfully completed SQL > / Enter value for v_no : 7369 SMITH CLERK 800 PL/SQL procedure successfully completed. 7.8 Explicit Cursors If SELECT statements in PL/SQL block return multiple rows then you have to explicitly create a cursor which is called as explicit cursor. The set of rows returned by a explicit cursor is called a result set. The row that is being processed is called the current row. Oracle uses four commands to handle Cursors. They are: a TT uy A> aol ty Puset jy, DECLARE : Defines the = f vith the SELECT statement, name and g i Me and structure of the cursor together with Execute: 2. OPEN es the query . determined Wery and the number of rows to be returned is 3. FETCH : Loads the row addre: and moves the cursor pointer or 4. CLOSE : Rele Ssed by the cursor pointer into variables 1 to the next row ready for the next fetch. aseS ithi ses the data within the cursor and closes it gyntax of explicit cursor : Cursor cursorname is SQL select statement; Cursor can be controlled using following 1. OPEN- Open statement identifi statement. 3 control statements. They are ics the active set...i.c. query returned by select Syntax of open cursor : open cursorname; 2. FETCH- close statement closes the cursor. Syntax of fetch : fetch cursorname into variable1, variable2. 3. CLOSE- fetch statement fetches rows into the variables...Cursors can be made into use using cursor for loop and fetch statement. Syntax of close : close cursorname; 2.7.9 Parameterised Cursor Syntax for declaring a parameterized cursor : CURSOR Cursorname (variable name Data type) is