0% found this document useful (0 votes)
63 views

Control Structures in PLSQL

The document discusses various control structures and cursors in PL/SQL. It describes the different types of control structures like IF-THEN-ELSE and iterative structures like basic loops, while loops, and for loops. It also discusses nested loops and how to use labels to identify loops. The document then covers implicit and explicit cursors, the steps to use explicit cursors including open, fetch, and close. It provides examples of declaring cursors and using them in blocks of code. It also discusses errors that may occur with cursors.

Uploaded by

udaykerun
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views

Control Structures in PLSQL

The document discusses various control structures and cursors in PL/SQL. It describes the different types of control structures like IF-THEN-ELSE and iterative structures like basic loops, while loops, and for loops. It also discusses nested loops and how to use labels to identify loops. The document then covers implicit and explicit cursors, the steps to use explicit cursors including open, fetch, and close. It provides examples of declaring cursors and using them in blocks of code. It also discusses errors that may occur with cursors.

Uploaded by

udaykerun
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 8

Control structures in PLSQL Each control structures to be used for different requirements All control structures works based

on the conditions Precautions in adding the conditions IF control statement works based on Y or N or NULL of the particular condition Nulls to be taken care properly with default values to return either Y / N by using NVL function If g_trace = Y then wrong If nvl (g_trace, N) = N then right. How do you identify the default value...? Based on default functionality. Every control structure will have entry condition and exit condition along with LOOP Each control structure may have set of conditions with various logical operators like AND, OR , NOT. In such cases , conditions combination chart to be referred. AND TRUE FALSE NULL TRUE TRUE FALSE NULL FALSE FALSE FALSE FALSE NULL NULL FALSE NULL OR TRUE FALSE NULL TRUE TRUE TRUE TRUE FALSE TRUE FALSE NULL NULL TRUE NULL NULL NOT TRUE FALSE NULL FALSE TRUE NULL

Difference between condition & Statement Simple Condition represents the comparison with LHS and RHS attributes with comparison operator. Complex condition represents with set of conditions with logical operator Any control structure can accept the complex conditions Entry conditions decide control focus to get into loop Exit condition decides to exit Logic between the loop will be continuously executed till exit criteria is met Conditional control statements IF ELSIIF END IF; Set of the logic check lists are known and only one checkpoint will be used by logic This control statement does not have a loop because only one option to be picked up. 1 checkpoint if end if 2 checkpoints (one with ve, another +V2) if else - end if 3. Checkpoints more then tow if elsif..Elsief...else. end if Entry criteria; If condition is true Iterative control statements Basic Loop; o Loop , logic, exit when, end loop o Entry criteria is without condition o Exit criteria is conditional , when condition is ture o Iteration , continuity will be continued till condition is ture

While Loop; o Loop , logic, exit when, end loop o Entry criteria is with true condition o Exit criteria is conditional , when condition is False o Iteration , continuity will be continued till condition is false For Loop o Loop logic will be exited when expected maximum no of iterations covered o Entry criteria , Counter variable will be initialized 1 check whether expected maximum counter is reached For I in 1.10 starts with zero in declaration, 1 is min, max is 10 o

Exit criteria is conditional , when maximum counter is reached Iteration, each iteration will be have set of logic with value incrementation in any language, but PL/SQL takes care of auto increment.

Nested Loop When loop is there in another loop, if we use exit when we will be confused, which loop to exit. Imagine when condition all loops to be exited. All above scenario, it is advisable to use labels for Loop Loop label can be given before loop Loop label can be mentioned in exit when condition between exit and when as mentioned below <<Outer loop>> Exit Outer loop when condition ------<<<Inner Loop>>> Loop Exit Inner Loop when Condition End Loop End Loop Loop

About Cursors in PLSQL Every SQL statement executed by the Oracle Server an individual cursor associated with it: has Cursors to be used when Select statement fetching the data more then one record. Inserting the mass data using the sub query to avoid performance hit on database.

Types based on execution model Implicit cursors: Declared for all DML and PL/SQL SELECT statements Explicit cursors: Implicit cursors: Whenever any select statement is executed, database server creates the implicit cursors and implicitly does open, fetch, Close. User /Developer may not know what is happening in the background. But oracle provided a provision to check no of records processed by using cursor attributes. Explicit Cursors: Declared and named by the programmer

Open, Fetch, Close steps to be followed Explicit cursor functions: Can process beyond the first row returned by the query, row by row Keep track of which row is currently being processed Allow the programmer to manually control explicit cursors in the PL/SQL block

Explicit cursors are classified as follows

Normal cursor Explicit open, fetch, close is required Parameterized cursors Explicit open, fetch, close is required. Apart from this cursor can accept parameters Cursor for loop processing No explicit open , fetch, close is not required. Automatically does the

OPEN CURSOR OPEN is an executable statement that performs the following operations: 1. Dynamically allocates memory for a context area that eventually contains crucial processing information. 2. 3. Parses the SELECT statement. Binds the input variablessets the value for the input variables by obtaining their memory addresses.

4. Identifies the active setthe set of rows that satisfy the search criteria. Rows in the active set are not retrieved into variables when the OPEN statement is executed. Rather, the FETCH statement retrieves the rows. 5. 6. 7. Positions the pointer just before the first row in the active set. Reads the data for the current row into the output PL/SQL variables. Advances the pointer to the next row in the identified set. The FETCH statement performs the following operations:

Open Curosrname (actual value or local variable) Open emp_cur(7788); Remaing exit condition , close cursor are the same like normal explicit cursor Only difference between explicit & Implicit cursor attributes are 1) implicit cursor may not requires cursor name if SQL%ROWCOUNT = 0 then if SQL%NOTFOUND THEN if SQL%FOUND THEN IF SQL%ISOPEN Execute Dbms_output.put_LINE(SQL %ROWCOUNT|| rows selected ); Explicit Cursors - Steps Declare -- Compiler will associate query to cursor variable Cursor EMP_CUR is select * from emp where deptno=10; begin Open -- Ready to read / Activated the record set but no record read, Curor query is not executed. 2) explicit cursor requires cursor name

if Cursorname%ROWCOUNT = 0 then if Cursorname %NOTFOUND THEN if Cursorname %FOUND THEN IF Cursorname %ISOPEN

Loop Fetch -- To read continuously, equalent to select statement. -- First hit to fetch first record, subsequently next record -- No redcord, raised exception Execute Dbms_output.put_LINE(EMP_CUR%ROWCOUNT|| rows selected ); Exit when complete records are read or when desired records are readd. End Loop; Close the cursor Exception / When others. End; To test fetch exception when no data found at 11th & 12 iteration Count no of records imagine 10 are there, create one counter, increment the vale with 1 and exit when counter >12; Soln: Exit when last record is read. EXIT when SQL%Notfond To test open exception Add two open cursor statements with same cursor name Soln: Check whether cursor is already open before calling the open cursor statement. EMP_CUR%ISOPEN before opening 1 2 3 4 5 6 7* DECLARE CURSOR C1 IS SELECT EMPNO FROM EMP; V_EMPNO VARCHAR2(10); BEGIN OPEN C1; OPEN C1; END; Solution 1 DECLARE 2 CURSOR C1 IS SELECT EMPNO FROM EMP; 3 V_EMPNO VARCHAR2(10); 4 BEGIN 5 OPEN C1; 6 if c1%isopen then 7 close c1; 8 end if; 9 OPEN C1; 10* END; SQL> /

ERROR at line 1: ORA-06511: PL/SQL: cursor already open ORA-06512: at line 2 ORA-06512: at line 6 PL/SQL procedure successfully completed. To test non existence cursor Use Open cursor with xxxcur which is not declared. BEGIN OPEN C1; END; OPEN C1; * ERROR at line 2: ORA-06550: line 2, column 7: PLS-00201: identifier 'C1' must be declared ORA-06550: line 2, column 2: PL/SQL: SQL Statement ignored

Declare cursor which does not fetch even single record use, Open & Fetch Soln: Before fetch at least to check 1 record exists in the query. IF EMP_CUR%Rowcount >0 Dont put exit statement in Cursor Loop and test ORA-20000: ORU-10027: buffer overflow, limit of 2000 bytes

ORA-06512: at "SYS.DBMS_OUTPUT", line 34 ORA-06512: at "SYS.DBMS_OUTPUT", line 81 ORA-06512: at line 8 Why to close the cursor. Depending on no of user sessions at site & Database server capacity, DBA will set Open_cusros oracle initialization parameters. In case any one of the programming unit is not closing the cursor, database raise the exception as No of open cursor exceed. As result of which none of the programming unit will work. Where do you write the feedback statements in cursor programming? Before exit when is ideal or before close cursor. How you can avoid the declaration of cursor By referring the cursor with query as sub query in execution block FOR CURSOR_NAME IN (QUERY); For EMP_record in (SELECT * From emp) Loop End loop; How do you lock the records in cursor By giving the FOR UPDATE NO WAIT in select statement at cursor declaration Where Current of Cursor name to be used in update or delete statement to lock current records of current table when records from join query is locked in declaration section NOTES: The FOR UPDATE Clause The SELECT ... FOR UPDATE statement identifies the rows that will be updated or deleted, then locks each row in the result set. This is useful when you want to base an update on the existing values in a row. In that case, you must make sure the row is not changed by another user before the update. The optional NOWAIT keyword tells Oracle not to wait if requested rows have been locked by another user. Control is immediately returned to your program so that it can do other work before trying again to acquire the lock. If you omit the NOWAIT keyword , Oracle waits until the rows are available. Errors Related Cursors:

1.

ORA-01000 - Maximum open cursors exceeded

If you want more cursors to be opened at the same time, shut the database, change INITSID.ORA or SPFILE and restart the database, or just execute: ALTER SYSTEM SET open_cursors=500 SCOPE=BOTH

2.

ORA-01001 - Invalid cursor

An ORA-01001 error occurs when a PL/SQL or a 3GL program attempts to use a cursor which has not yet been opened, or which has already been closed.

Error Handling In PLSQL : Errors are three types 1) Compilation errors which can be sorted out during the code compilation time. 2) Implicit Run time errors (Exceptions) due to a. Logic handled is not followed properly . Example cursor exceptions

Some of the statements /queries require some pre-defined exceptions to handle due to unpredicted data. i. Ex: Select statement (No_data found,Too_many) ii. Ex: select statement with to_number (Invalid number) c. Pragma violations Note: Implicit exceptions are nothing but oracle errors which is of pre-defined & Non predefined exceptions 3) Run time errors due to explicit raising (User defined exceptions) Trapping a Non predefined Oracle Server Exception

b.

1. Declare the name for the exception within the declarative section. 2.
Syntax PRAGMAEXCEPTION_INIT(exception, error_number); where: exceptionis the previously declared exception. error_number is a standard Oracle Server error number. 3. Reference the declared exception within the corresponding exception-handling routine. The RAISE_APPLICATION_ERROR Procedure Syntax: RAISE_APPLICATION_ERROR (error_number, message); Associate the declared exception with the standard Oracle server error number using the PRAGMA EXCEPTION_INIT statement.

You can use this procedure to issue user-defined error messages from stored subprograms. You can report errors to your application and avoid returning unhandled exceptions. Used in two different places: - Executable section - Exception section

Returns error conditions to the user in a manner consistent with other Oracle server errors

Why to handle the exceptons ? To know unanticipated errors due to logic or data or certain queries/statement might not have been handled with exceptions To identify the successful exception by (exception raised and it is taken care) or no exceptions are raised. How do you handle the exceptions? Each block will have exception section with predicted exception handlers & When other also. Parent block must have when others but enclosed block may or may not. Based on the business requirement, incase if explicit exception to be raised, we will raise in user defined exception model Explain one user defined exception you have handled? I have not used user defined exception. Incase if user defined exceptions are used, forms front end developer need to check oracle exception by using DBMS_ERROR_CODE & DBMS_ERROR_TEXT once again after procedure execution.

In our application development process each procedure gives error_text as an output which was written based on business requirements. Application developer will not wait for user defined exception to come from Oracle Server; rather, he will take the error text from the procedure and display in alert. When to use, oracle is not a mad guy Incase if same exception to be raised in more then one procedure, in such cases, exception will be defined in package specification, which will be used across the packaged procedures by referring the raise exception in execution block and handle it in exception block. Can I add when others as first handle No. if it is done, all exceptions will be trapped in when others only. Subsequent exception will be waste. Can I use any other queries or procedure, function calls with in the exception block? Yes. Test for dup_val_on_index to update the data. Eg : BEGIN INSERT INTO DEPT(DEPTNO,DNAME,LOC) VALUES (10,'XXX','XXXX'); EXCEPTION WHEN DUP_VAL_ON_INDEX THEN UPDATE DEPART SET LOC = 'HYDERABAD' WHERE DEPTNO = 10; WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(SQLCODE||' : '||SQLERRM); END; / What are the error trapping functions SQLCODE which returns oracle server error code SQLERRM which returns oracle error message. Transaction successfully completed message can be given when sqlerrcode=0 Display the user defined error by using SQLERRM function when SQLERRCODE=1 Else display the relevant error message. But preferred to customize this error message before display to give the clear picture to end users. When to use raise application error? Advised to use in when others If we are not interested to use user defined exception which is in 3 steps. Raise application error can be achieved in one step. What is the difference in raise application error & user defined exception User defined exception can be reused Raise application error is one time use Steps are different in both. What is exception Propagation When a sub block handles an exception, it terminates normally, and control resumes in the enclosing block immediately after the sub block END statement. However, if PL/SQL raises an exception and the current block does not have a handler for that exception, the exception propagates in successive enclosing blocks until it finds a handler. If none of these blocks handle the exception, an unhandled exception in the host environment results. When the exception propagates to an enclosing block, the remaining executable actions in that block are bypassed. List Some Pre Defined Exceptions

STORAGE_ERROR

ORA-06500

PL/SQL ran out of memory or memory is corrupted. The conversion of a character string into auniversal ROWID fails because the characterstring does not represent a valid ROWID. Time-out occurred while Oracle is waiting for a resource. Single-row SELECT returned more than one row Arithmetic, conversion, truncation, or size-constraint error occurred. Attempted to divide by zero Attempted to assign values to the attributes of an uninitialized object None of the choices in the WHEN clauses of a CASE statement is selected, and there is no ELSE clause. than EXISTS to an uninitialized nested table or varray Attempted to open an already open cursor Attempted to insert a duplicate value Illegal cursor operation occurred Conversion of character string to number fails Logging on to Oracle with an invalid username or password Single row SELECT returned no data PL/SQL program issues a database call without being connected to Oracle PL/SQL has an internal problem Host cursor variable and PL/SQL cursor variable involved in an assignment have incompatible return types

SYS_INVALID_ROWID TIMEOUT_ON_RESOURCE TOO_MANY_ROWS VALUE_ERROR ZERO_DIVIDE ACCESS_INTO_NULL CASE_NOT_FOUND CURSOR_ALREADY_OPEN DUP_VAL_ON_INDEX INVALID_CURSOR INVALID_NUMBER LOGIN_DENIED NO_DATA_FOUND NOT_LOGGED_ON PROGRAM_ERROR ROWTYPE_MISMATCH

ORA-01410 ORA-00051 ORA-01422 ORA-06502 ORA-01476 ORA-06530 ORA-06592 ORA-06511 ORA-00001 ORA-01001 ORA-01722 ORA-01017 ORA-01403 ORA-01012 ORA-06501 ORA-06504

You might also like