Presentation is loading. Please wait.

Presentation is loading. Please wait.

PL/SQLPL/SQL Declaring Variables Declaring Variables Declaring Variables Declaring Variables Writing Executable Statements Writing Executable Statements.

Similar presentations


Presentation on theme: "PL/SQLPL/SQL Declaring Variables Declaring Variables Declaring Variables Declaring Variables Writing Executable Statements Writing Executable Statements."— Presentation transcript:

1

2 PL/SQLPL/SQL Declaring Variables Declaring Variables Declaring Variables Declaring Variables Writing Executable Statements Writing Executable Statements Writing Executable Statements Writing Executable Statements Interacting with the Oracle Server Interacting with the Oracle Server Interacting with the Oracle Server Interacting with the Oracle Server Writing Control Structures Writing Control Structures Writing Control Structures Writing Control Structures Working with Composite Datatypes Working with Composite Datatypes Working with Composite Datatypes Working with Composite Datatypes Cursors Cursors Cursors Handling Exceptions Handling Exceptions Handling Exceptions Handling Exceptions Declaring Variables Declaring Variables Declaring Variables Declaring Variables Writing Executable Statements Writing Executable Statements Writing Executable Statements Writing Executable Statements Interacting with the Oracle Server Interacting with the Oracle Server Interacting with the Oracle Server Interacting with the Oracle Server Writing Control Structures Writing Control Structures Writing Control Structures Writing Control Structures Working with Composite Datatypes Working with Composite Datatypes Working with Composite Datatypes Working with Composite Datatypes Cursors Cursors Cursors Handling Exceptions Handling Exceptions Handling Exceptions Handling Exceptions

3 Declaring Variables

4 ObjectivesObjectives After completing this lesson, you should be able to do the following: After completing this lesson, you should be able to do the following: List the benefits of PL/SQL List the benefits of PL/SQL Recognize the basic PL/SQL block and its sections Recognize the basic PL/SQL block and its sections Describe the significance of variables in PL/SQL Describe the significance of variables in PL/SQL Declare PL/SQL variables Declare PL/SQL variables Execute a PL/SQL block Execute a PL/SQL block After completing this lesson, you should be able to do the following: After completing this lesson, you should be able to do the following: List the benefits of PL/SQL List the benefits of PL/SQL Recognize the basic PL/SQL block and its sections Recognize the basic PL/SQL block and its sections Describe the significance of variables in PL/SQL Describe the significance of variables in PL/SQL Declare PL/SQL variables Declare PL/SQL variables Execute a PL/SQL block Execute a PL/SQL block

5 About PL/SQL PL/SQL is an extension to SQL with design features of programming languages. PL/SQL is an extension to SQL with design features of programming languages. Data manipulation and query statements of SQL are included within procedural units of code. Data manipulation and query statements of SQL are included within procedural units of code. PL/SQL is an extension to SQL with design features of programming languages. PL/SQL is an extension to SQL with design features of programming languages. Data manipulation and query statements of SQL are included within procedural units of code. Data manipulation and query statements of SQL are included within procedural units of code.

6 PL/SQL Block Structure DECLARE – Optional Variables, cursors, user-defined exceptions BEGIN – Mandatory – SQL statements – PL/SQL statements EXCEPTION – Optional Actions to perform when errors occur END; – Mandatory DECLARE – Optional Variables, cursors, user-defined exceptions BEGIN – Mandatory – SQL statements – PL/SQL statements EXCEPTION – Optional Actions to perform when errors occur END; – Mandatory DECLARE BEGIN EXCEPTION END;

7 PL/SQL Block Structure DECLARE v_variable VARCHAR2(5); BEGIN SELECTcolumn_name INTOv_variable FROMtable_name; EXCEPTION WHEN exception_name THEN... END; DECLARE v_variable VARCHAR2(5); BEGIN SELECTcolumn_name INTOv_variable FROMtable_name; EXCEPTION WHEN exception_name THEN... END; DECLARE BEGIN EXCEPTION END;

8 Block Types AnonymousProcedureFunction AnonymousProcedureFunction [DECLARE]BEGIN --statements --statements[EXCEPTION]END;[DECLARE]BEGIN [EXCEPTION]END; PROCEDURE name ISBEGIN --statements --statements[EXCEPTION]END; PROCEDURE name ISBEGIN --statements --statements[EXCEPTION]END; FUNCTION name RETURN datatype ISBEGIN --statements --statements RETURN value; RETURN value;[EXCEPTION]END; FUNCTION name RETURN datatype ISBEGIN --statements --statements RETURN value; RETURN value;[EXCEPTION]END;

9 Program Constructs Anonymous block Application trigger Stored procedure/ function Database trigger Application procedure/ function Packaged procedure/ function function DECLARE BEGIN EXCEPTION END;

10 Types of Variables PL/SQL variables: PL/SQL variables: Scalar Scalar Composite Composite Reference Reference LOB (large objects) LOB (large objects) Non-PL/SQL variables: Bind and host variables Non-PL/SQL variables: Bind and host variables PL/SQL variables: PL/SQL variables: Scalar Scalar Composite Composite Reference Reference LOB (large objects) LOB (large objects) Non-PL/SQL variables: Bind and host variables Non-PL/SQL variables: Bind and host variables

11 TRUE Types of Variables 25-OCT-99 25-OCT-99 Atlanta 256120.08 256120.08

12 Declaring PL/SQL Variables SyntaxExamplesSyntaxExamples identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr]; identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr]; Declare v_hiredateDATE; v_deptnoNUMBER(2) NOT NULL := 10; v_locationVARCHAR2(13) := 'Atlanta'; c_commCONSTANT NUMBER := 1400; Declare v_hiredateDATE; v_deptnoNUMBER(2) NOT NULL := 10; v_locationVARCHAR2(13) := 'Atlanta'; c_commCONSTANT NUMBER := 1400;

13 Declaring PL/SQL Variables Guidelines Guidelines Follow naming conventions. Follow naming conventions. Initialize variables designated as NOT NULL and CONSTANT. Initialize variables designated as NOT NULL and CONSTANT. Initialize identifiers by using the assignment operator (:=) or the DEFAULT reserved word. Initialize identifiers by using the assignment operator (:=) or the DEFAULT reserved word. Declare at most one identifier per line. Declare at most one identifier per line. Guidelines Guidelines Follow naming conventions. Follow naming conventions. Initialize variables designated as NOT NULL and CONSTANT. Initialize variables designated as NOT NULL and CONSTANT. Initialize identifiers by using the assignment operator (:=) or the DEFAULT reserved word. Initialize identifiers by using the assignment operator (:=) or the DEFAULT reserved word. Declare at most one identifier per line. Declare at most one identifier per line.

14 Naming Rules Two variables can have the same name, provided they are in different blocks. Two variables can have the same name, provided they are in different blocks. The variable name (identifier) should not be the same as the name of table columns used in the block. The variable name (identifier) should not be the same as the name of table columns used in the block. Two variables can have the same name, provided they are in different blocks. Two variables can have the same name, provided they are in different blocks. The variable name (identifier) should not be the same as the name of table columns used in the block. The variable name (identifier) should not be the same as the name of table columns used in the block. DECLARE empnoNUMBER(4); BEGIN SELECTempno INTOempno FROMemp WHERE ename = 'SMITH'; END; DECLARE empnoNUMBER(4); BEGIN SELECTempno INTOempno FROMemp WHERE ename = 'SMITH'; END; Adopt a naming convention for PL/SQL identifiers: for example, v_empno Adopt a naming convention for PL/SQL identifiers: for example, v_empno

15 Assigning Values to Variables v_ename := 'Maduro'; v_hiredate := '31-DEC-98'; SyntaxExamples Set a predefined hiredate for new employees. SyntaxExamples Set the employee name to Maduro. identifier := expr;

16 Scalar Datatypes Hold a single value Have no internal components Hold a single value Have no internal components 25-OCT-99 25-OCT-99 Atlanta TRUE 256120.08 256120.08

17 Base Scalar Datatypes VARCHAR2 (maximum_length) VARCHAR2 (maximum_length) NUMBER [(precision, scale)] NUMBER [(precision, scale)] DATE DATE CHAR [(maximum_length)] CHAR [(maximum_length)] LONG LONG BOOLEAN BOOLEAN BINARY_INTEGER BINARY_INTEGER VARCHAR2 (maximum_length) VARCHAR2 (maximum_length) NUMBER [(precision, scale)] NUMBER [(precision, scale)] DATE DATE CHAR [(maximum_length)] CHAR [(maximum_length)] LONG LONG BOOLEAN BOOLEAN BINARY_INTEGER BINARY_INTEGER

18 Scalar Variable Declarations v_jobVARCHAR2(9); v_countBINARY_INTEGER := 0; v_total_salNUMBER(9,2) := 0; v_orderdateDATE := SYSDATE + 7; c_tax_rateCONSTANT NUMBER(3,2) := 8.25; v_validBOOLEAN NOT NULL := TRUE; v_jobVARCHAR2(9); v_countBINARY_INTEGER := 0; v_total_salNUMBER(9,2) := 0; v_orderdateDATE := SYSDATE + 7; c_tax_rateCONSTANT NUMBER(3,2) := 8.25; v_validBOOLEAN NOT NULL := TRUE; Examples Examples

19 The %TYPE Attribute Declare a variable according to: Declare a variable according to: A database column definition A database column definition Another previously declared variable Another previously declared variable Prefix %TYPE with: Prefix %TYPE with: The database table and column The database table and column The previously declared variable name The previously declared variable name Declare a variable according to: Declare a variable according to: A database column definition A database column definition Another previously declared variable Another previously declared variable Prefix %TYPE with: Prefix %TYPE with: The database table and column The database table and column The previously declared variable name The previously declared variable name

20 Declaring Variables with the %TYPE Attribute Examples Examples... v_enameemp.ename%TYPE; v_balanceNUMBER(7,2); v_min_balancev_balance%TYPE := 10;... v_enameemp.ename%TYPE; v_balanceNUMBER(7,2); v_min_balancev_balance%TYPE := 10;...

21 Declaring Boolean Variables Only the values TRUE, FALSE, and NULL can be assigned to a Boolean variable. Only the values TRUE, FALSE, and NULL can be assigned to a Boolean variable. The variables are connected by the logical operators AND, OR, and NOT. The variables are connected by the logical operators AND, OR, and NOT. The variables always yield TRUE, FALSE, or NULL. The variables always yield TRUE, FALSE, or NULL. Arithmetic, character, and date expressions can be used to return a Boolean value. Arithmetic, character, and date expressions can be used to return a Boolean value. Only the values TRUE, FALSE, and NULL can be assigned to a Boolean variable. Only the values TRUE, FALSE, and NULL can be assigned to a Boolean variable. The variables are connected by the logical operators AND, OR, and NOT. The variables are connected by the logical operators AND, OR, and NOT. The variables always yield TRUE, FALSE, or NULL. The variables always yield TRUE, FALSE, or NULL. Arithmetic, character, and date expressions can be used to return a Boolean value. Arithmetic, character, and date expressions can be used to return a Boolean value.

22 15000 22345 312 43456 1SMITH 2JONES 3NANCY 4TIM PL/SQL table structure BINARY_INTEGER VARCHAR2 BINARY_INTEGER NUMBER PL/SQL Record Structure TRUE 23-DEC-98ATLANTA

23 LOB Datatype Variables Book(CLOB) Photo(BLOB) Movie(BFILE) NCLOB

24 Bind Variables Example SQL>Variable m_sal NUMBER SQL>Variable m_sal NUMBER SQL>Set SERVEROUTPUT ON SQL>Set SERVEROUTPUT ON SQL>Declare SQL>Declare V_sal NUMBER; V_sal NUMBER; Begin Begin :m_sal :=300; :m_sal :=300; V_sal=&m_sal; V_sal=&m_sal; DBMS_OUTPUT.PUT_LINE(‘salary is: ‘||v_sal); DBMS_OUTPUT.PUT_LINE(‘salary is: ‘||v_sal); End; End; SQL>Print m_sal SQL>Print m_sal

25 Writing Executable Statements

26 PL/SQL Block Syntax and Guidelines Identifiers Identifiers Can contain up to 30 characters Can contain up to 30 characters Cannot contain reserved words unless enclosed in double quotation marks Cannot contain reserved words unless enclosed in double quotation marks Must begin with an alphabetic character Must begin with an alphabetic character Should not have the same name as a database table column name Should not have the same name as a database table column name Identifiers Identifiers Can contain up to 30 characters Can contain up to 30 characters Cannot contain reserved words unless enclosed in double quotation marks Cannot contain reserved words unless enclosed in double quotation marks Must begin with an alphabetic character Must begin with an alphabetic character Should not have the same name as a database table column name Should not have the same name as a database table column name

27 PL/SQL Block Syntax and Guidelines Literals Literals Character and date literals must be enclosed in single quotation marks. Character and date literals must be enclosed in single quotation marks. A PL/SQL block is terminated by a slash ( / ) on a line by itself. A PL/SQL block is terminated by a slash ( / ) on a line by itself. Literals Literals Character and date literals must be enclosed in single quotation marks. Character and date literals must be enclosed in single quotation marks. A PL/SQL block is terminated by a slash ( / ) on a line by itself. A PL/SQL block is terminated by a slash ( / ) on a line by itself. v_ename := 'Henderson';

28 Commenting Code Prefix single-line comments with two dashes (-- ). Prefix single-line comments with two dashes (-- ). Place multi-line comments between the symbols /* and */. Place multi-line comments between the symbols /* and */. Example Example Prefix single-line comments with two dashes (-- ). Prefix single-line comments with two dashes (-- ). Place multi-line comments between the symbols /* and */. Place multi-line comments between the symbols /* and */. Example Example... v_sal NUMBER (9,2); BEGIN /* Compute the annual salary based on the monthly salary input from the user */ v_sal := &p_monthly_sal * 12; END; -- This is the end of the block... v_sal NUMBER (9,2); BEGIN /* Compute the annual salary based on the monthly salary input from the user */ v_sal := &p_monthly_sal * 12; END; -- This is the end of the block

29 PL/SQL Functions Examples Examples Build the mailing list for a company. Build the mailing list for a company. Convert the employee name to lowercase. Convert the employee name to lowercase. Examples Examples Build the mailing list for a company. Build the mailing list for a company. Convert the employee name to lowercase. Convert the employee name to lowercase. v_mailing_address := v_name||CHR(10)|| v_address||CHR(10)||v_state|| CHR(10)||v_zip; v_mailing_address := v_name||CHR(10)|| v_address||CHR(10)||v_state|| CHR(10)||v_zip; v_ename:= LOWER(v_ename);

30 Datatype Conversion Convert data to comparable datatypes. Convert data to comparable datatypes. Mixed datatypes can result in an error and affect performance. Mixed datatypes can result in an error and affect performance. Conversion functions: Conversion functions: TO_CHAR TO_CHAR TO_DATE TO_DATE TO_NUMBER TO_NUMBER Convert data to comparable datatypes. Convert data to comparable datatypes. Mixed datatypes can result in an error and affect performance. Mixed datatypes can result in an error and affect performance. Conversion functions: Conversion functions: TO_CHAR TO_CHAR TO_DATE TO_DATE TO_NUMBER TO_NUMBER DECLARE v_date VARCHAR2(15); BEGIN SELECT TO_CHAR(hiredate, 'MON. DD, YYYY') INTO v_date FROM emp WHERE empno = 7839; END; DECLARE v_date VARCHAR2(15); BEGIN SELECT TO_CHAR(hiredate, 'MON. DD, YYYY') INTO v_date FROM emp WHERE empno = 7839; END;

31 Datatype Conversion This statement produces a compilation error if the variable v_date is declared as datatype DATE. v_date := 'January 13, 1998'; v_date := TO_DATE ('January 13, 1998', 'Month DD, YYYY'); v_date := TO_DATE ('January 13, 1998', 'Month DD, YYYY'); To correct the error, use the TO_DATE conversion function.

32 Nested Blocks and Variable Scope The body and the exception parts in the PL/SQL block could contain nested blocks. The body and the exception parts in the PL/SQL block could contain nested blocks. An identifier is visible in the regions in which you can reference the identifier: An identifier is visible in the regions in which you can reference the identifier: A block can look up to the enclosing block. A block can look up to the enclosing block. A block cannot look down to enclosed blocks. A block cannot look down to enclosed blocks. The body and the exception parts in the PL/SQL block could contain nested blocks. The body and the exception parts in the PL/SQL block could contain nested blocks. An identifier is visible in the regions in which you can reference the identifier: An identifier is visible in the regions in which you can reference the identifier: A block can look up to the enclosing block. A block can look up to the enclosing block. A block cannot look down to enclosed blocks. A block cannot look down to enclosed blocks.

33 Nested Blocks and Variable Scope... x BINARY_INTEGER; BEGIN... DECLARE y NUMBER; BEGIN... END;... END;... x BINARY_INTEGER; BEGIN... DECLARE y NUMBER; BEGIN... END;... END; Scope of x Scope of y Example

34 Nested Blocks Example SQL> DECLARE SQL> DECLARE v_m VARCHAR2(50) :='Oracle'; v_m VARCHAR2(50) :='Oracle'; BEGIN BEGIN DECLARE DECLARE v_z VARCHAR2(20):='Second'; v_z VARCHAR2(20):='Second'; BEGIN BEGIN v_m:=v_m || v_z; v_m:=v_m || v_z; END; END; v_m:=v_m || ‘ Exam'; v_m:=v_m || ‘ Exam'; DBMS_OUTPUT.PUT_LINE(v_m); DBMS_OUTPUT.PUT_LINE(v_m); END; END; / Output: Oracle Second Exam

35 The PL/SQL operators are generally the same as those of SQL(Arithmetic, logical,..) The PL/SQL operators are generally the same as those of SQL(Arithmetic, logical,..) ** is the exponential operator in PL/SQL ** is the exponential operator in PL/SQL dbms_output.put_line(2**3); --Output is 8 dbms_output.put_line(2**3); --Output is 8 Comparison involving null always yield null Comparison involving null always yield null Examples Examples V_count := v_count+1; V_count := v_count+1; V_equal :=(v_n1=v_n2); V_equal :=(v_n1=v_n2); V_valid :=(v_empno IS NOT NULL); V_valid :=(v_empno IS NOT NULL); The PL/SQL operators are generally the same as those of SQL(Arithmetic, logical,..) The PL/SQL operators are generally the same as those of SQL(Arithmetic, logical,..) ** is the exponential operator in PL/SQL ** is the exponential operator in PL/SQL dbms_output.put_line(2**3); --Output is 8 dbms_output.put_line(2**3); --Output is 8 Comparison involving null always yield null Comparison involving null always yield null Examples Examples V_count := v_count+1; V_count := v_count+1; V_equal :=(v_n1=v_n2); V_equal :=(v_n1=v_n2); V_valid :=(v_empno IS NOT NULL); V_valid :=(v_empno IS NOT NULL); Operators in PL/SQL

36 Programming Guidelines Use comments Use comments Use a case convention for the code Use a case convention for the code Write keywords in uppercase Write keywords in uppercase Write identifiers in lowercase Write identifiers in lowercase Use naming convention for identifiers Use naming convention for identifiers Variables: v_name Variables: v_name Constants: c_name Constants: c_name … Use Indentation Use Indentation Use comments Use comments Use a case convention for the code Use a case convention for the code Write keywords in uppercase Write keywords in uppercase Write identifiers in lowercase Write identifiers in lowercase Use naming convention for identifiers Use naming convention for identifiers Variables: v_name Variables: v_name Constants: c_name Constants: c_name … Use Indentation Use Indentation

37 Indenting Code For clarity, indent each level of code. For clarity, indent each level of code. Example Example For clarity, indent each level of code. For clarity, indent each level of code. Example Example BEGIN IF x=0 THEN y:=1; END IF; END; BEGIN IF x=0 THEN y:=1; END IF; END; DECLARE v_deptnoNUMBER(2); v_locationVARCHAR2(13); BEGIN SELECTdeptno, loc INTOv_deptno, v_location FROMdept WHEREdname = 'SALES';... END; DECLARE v_deptnoNUMBER(2); v_locationVARCHAR2(13); BEGIN SELECTdeptno, loc INTOv_deptno, v_location FROMdept WHEREdname = 'SALES';... END;

38 Determining Variable Scope Class Exercise Class Exercise... DECLARE V_SALNUMBER(7,2) := 60000; V_COMMNUMBER(7,2) := V_SAL *.20; V_MESSAGEVARCHAR2(255) := ' eligible for commission'; BEGIN... DECLARE V_SALNUMBER(7,2) := 50000; V_COMM NUMBER(7,2) := 0; V_TOTAL_COMPNUMBER(7,2) := V_SAL + V_COMM; BEGIN... V_MESSAGE := 'CLERK not'||V_MESSAGE; END; V_MESSAGE := 'SALESMAN'||V_MESSAGE; END;... DECLARE V_SALNUMBER(7,2) := 60000; V_COMMNUMBER(7,2) := V_SAL *.20; V_MESSAGEVARCHAR2(255) := ' eligible for commission'; BEGIN... DECLARE V_SALNUMBER(7,2) := 50000; V_COMM NUMBER(7,2) := 0; V_TOTAL_COMPNUMBER(7,2) := V_SAL + V_COMM; BEGIN... V_MESSAGE := 'CLERK not'||V_MESSAGE; END; V_MESSAGE := 'SALESMAN'||V_MESSAGE; END;

39 Interacting with the Oracle Server

40 PL/SQL Statements Valid PL/SQL statements: DML commands DML commands Some DCL commands (Commit, rollack, savepoint,…) Some DCL commands (Commit, rollack, savepoint,…) Invalid PL/SQL statements: DDL commands DDL commands Some DCL commands (Grant, Revoke,…) Some DCL commands (Grant, Revoke,…)

41 SELECT Statements in PL/SQL Retrieve data from the database with SELECT. Retrieve data from the database with SELECT. Syntax Syntax Retrieve data from the database with SELECT. Retrieve data from the database with SELECT. Syntax Syntax SELECT select_list INTO {variable_name[, variable_name]... | record_name} FROM table WHERE condition;

42 SELECT Statements in PL/SQL The INTO clause is required. The INTO clause is required. Example Example The INTO clause is required. The INTO clause is required. Example Example DECLARE v_deptnoNUMBER(2); v_locVARCHAR2(15); BEGIN SELECTdeptno, loc INTOv_deptno, v_loc FROMdept WHEREdname = 'SALES';... END; DECLARE v_deptnoNUMBER(2); v_locVARCHAR2(15); BEGIN SELECTdeptno, loc INTOv_deptno, v_loc FROMdept WHEREdname = 'SALES';... END;

43 Retrieving Data in PL/SQL Retrieve the order date and the ship date for the specified order. Retrieve the order date and the ship date for the specified order. Example Example Retrieve the order date and the ship date for the specified order. Retrieve the order date and the ship date for the specified order. Example Example DECLARE v_orderdate ord.orderdate%TYPE; v_shipdate ord.shipdate%TYPE; BEGIN SELECT orderdate, shipdate INTO v_orderdate, v_shipdate FROM ord WHERE id = 620;... END; DECLARE v_orderdate ord.orderdate%TYPE; v_shipdate ord.shipdate%TYPE; BEGIN SELECT orderdate, shipdate INTO v_orderdate, v_shipdate FROM ord WHERE id = 620;... END;

44 Retrieving Data in PL/SQL Return the sum of the salaries for all employees in the specified department. Return the sum of the salaries for all employees in the specified department. Example Example Return the sum of the salaries for all employees in the specified department. Return the sum of the salaries for all employees in the specified department. Example Example DECLARE v_sum_sal emp.sal%TYPE; v_deptno NUMBER NOT NULL := 10; BEGIN SELECTSUM(sal) -- group function INTOv_sum_sal FROMemp WHEREdeptno = v_deptno; END;

45 INSERTUPDATEDELETE Manipulating Data Using PL/SQL Make changes to database tables by using DML commands: Make changes to database tables by using DML commands: INSERT INSERT UPDATE UPDATE DELETE DELETE Make changes to database tables by using DML commands: Make changes to database tables by using DML commands: INSERT INSERT UPDATE UPDATE DELETE DELETE

46 Inserting Data Add new employee information to the EMP table. Add new employee information to the EMP table. Example Example Add new employee information to the EMP table. Add new employee information to the EMP table. Example Example BEGIN INSERT INTO emp(empno, ename, job, deptno) VALUES(empno_sequence.NEXTVAL, 'HARDING', 'CLERK', 10); END; BEGIN INSERT INTO emp(empno, ename, job, deptno) VALUES(empno_sequence.NEXTVAL, 'HARDING', 'CLERK', 10); END;

47 Updating Data Increase the salary of all employees in the EMP table who are Analysts. Increase the salary of all employees in the EMP table who are Analysts. Example Example Increase the salary of all employees in the EMP table who are Analysts. Increase the salary of all employees in the EMP table who are Analysts. Example Example DECLARE v_sal_increase emp.sal%TYPE := 2000; BEGIN UPDATEemp SETsal = sal + v_sal_increase WHEREjob = 'ANALYST'; END;

48 Deleting Data Delete rows that belong to department 10 from the EMP table. Delete rows that belong to department 10 from the EMP table. Example Example Delete rows that belong to department 10 from the EMP table. Delete rows that belong to department 10 from the EMP table. Example Example DECLARE v_deptno emp.deptno%TYPE := 10; BEGIN DELETE FROM emp WHERE deptno = v_deptno; END; DECLARE v_deptno emp.deptno%TYPE := 10; BEGIN DELETE FROM emp WHERE deptno = v_deptno; END;

49 Naming Conventions DECLARE orderdateord.orderdate%TYPE; shipdate ord.shipdate%TYPE; ordid ord.ordid%TYPE := 601; BEGIN SELECT orderdate, shipdate INTO orderdate, shipdate FROM ord WHERE ordid = ordid; END; SQL> / DECLARE * ERROR at line 1: ORA-01422: exact fetch returns more than requested number of rows ORA-06512: at line 6 DECLARE orderdateord.orderdate%TYPE; shipdate ord.shipdate%TYPE; ordid ord.ordid%TYPE := 601; BEGIN SELECT orderdate, shipdate INTO orderdate, shipdate FROM ord WHERE ordid = ordid; END; SQL> / DECLARE * ERROR at line 1: ORA-01422: exact fetch returns more than requested number of rows ORA-06512: at line 6

50 Writing Control Structures

51 Controlling PL/SQL Flow of Execution You can change the logical flow of statements using conditional IF statements and loop control structures. You can change the logical flow of statements using conditional IF statements and loop control structures. Conditional IF statements: Conditional IF statements: IF-THEN-END IF IF-THEN-END IF IF-THEN-ELSE-END IF IF-THEN-ELSE-END IF IF-THEN-ELSIF-END IF IF-THEN-ELSIF-END IF You can change the logical flow of statements using conditional IF statements and loop control structures. You can change the logical flow of statements using conditional IF statements and loop control structures. Conditional IF statements: Conditional IF statements: IF-THEN-END IF IF-THEN-END IF IF-THEN-ELSE-END IF IF-THEN-ELSE-END IF IF-THEN-ELSIF-END IF IF-THEN-ELSIF-END IF

52 IF Statements IF condition THEN statements; [ELSIF condition THEN statements;] [ELSE statements;] END IF; IF condition THEN statements; [ELSIF condition THEN statements;] [ELSE statements;] END IF; Syntax Simple IF statement: Set the manager ID to 22 if the employee name is Osborne. Syntax Simple IF statement: Set the manager ID to 22 if the employee name is Osborne. IF v_ename = 'OSBORNE' THEN v_mgr := 22; END IF; IF v_ename = 'OSBORNE' THEN v_mgr := 22; END IF;

53 Simple IF Statements Set the job title to Salesman, the department number to 35, and the commission to 20% of the current salary if the last name is Miller. Set the job title to Salesman, the department number to 35, and the commission to 20% of the current salary if the last name is Miller. Example Example Set the job title to Salesman, the department number to 35, and the commission to 20% of the current salary if the last name is Miller. Set the job title to Salesman, the department number to 35, and the commission to 20% of the current salary if the last name is Miller. Example Example... IF v_ename = 'MILLER' THEN v_job := 'SALESMAN'; v_deptno := 35; v_new_comm := sal * 0.20; END IF;... IF v_ename = 'MILLER' THEN v_job := 'SALESMAN'; v_deptno := 35; v_new_comm := sal * 0.20; END IF;...

54 IF-THEN-ELSE Statement Execution Flow IF condition TRUE THEN actions (including further IFs) THEN actions (including further IFs) FALSE ELSE actions (including further IFs) ELSE actions (including further IFs)

55 IF-THEN-ELSE Statements Set a flag for orders where there are fewer than five days between order date and ship date. Set a flag for orders where there are fewer than five days between order date and ship date. Example Example Set a flag for orders where there are fewer than five days between order date and ship date. Set a flag for orders where there are fewer than five days between order date and ship date. Example Example... IF v_shipdate - v_orderdate < 5 THEN v_ship_flag := 'Acceptable'; ELSE v_ship_flag := 'Unacceptable'; END IF;... IF v_shipdate - v_orderdate < 5 THEN v_ship_flag := 'Acceptable'; ELSE v_ship_flag := 'Unacceptable'; END IF;...

56 IF-THEN-ELSIF Statement Execution Flow IF condition TRUE THEN actions FALSE ELSIFconditionELSIFcondition TRUE FALSE ELSEactionsELSEactions

57 IF-THEN-ELSIF Statements For a given value, calculate a percentage of that value based on a condition. For a given value, calculate a percentage of that value based on a condition. Example Example For a given value, calculate a percentage of that value based on a condition. For a given value, calculate a percentage of that value based on a condition. Example Example... IF v_start > 100 THEN v_start := 2 * v_start; ELSIF v_start >= 50 THEN v_start :=.5 * v_start; ELSE v_start :=.1 * v_start; END IF;... IF v_start > 100 THEN v_start := 2 * v_start; ELSIF v_start >= 50 THEN v_start :=.5 * v_start; ELSE v_start :=.1 * v_start; END IF;...

58 Building Logical Conditions You can handle null values with the IS NULL operator. You can handle null values with the IS NULL operator. Any arithmetic expression containing a null value evaluates to NULL. Any arithmetic expression containing a null value evaluates to NULL. Concatenated expressions with null values treat null values as an empty string. Concatenated expressions with null values treat null values as an empty string. NULL acts as False NULL acts as False You can handle null values with the IS NULL operator. You can handle null values with the IS NULL operator. Any arithmetic expression containing a null value evaluates to NULL. Any arithmetic expression containing a null value evaluates to NULL. Concatenated expressions with null values treat null values as an empty string. Concatenated expressions with null values treat null values as an empty string. NULL acts as False NULL acts as False

59 Logic Tables Build a simple Boolean condition with a comparison operator. Build a simple Boolean condition with a comparison operator. NOT TRUE FALSE NULL OR TRUE FALSE NULL TRUEFALSENULL FALSE TRUE NULL AND TRUE FALSE NULL TRUEFALSENULL TRUE NULL FALSE TRUE FALSE NULL

60 Boolean Conditions What is the value of V_FLAG in each case? What is the value of V_FLAG in each case? V_REORDER_FLAGV_AVAILABLE_FLAGV_FLAG TRUE TRUEFALSE NULLTRUE NULLFALSE v_flag := v_reorder_flag AND v_available_flag; TRUEFALSENULLFALSE

61 Iterative Control: LOOP Statements Loops repeat a statement or sequence of statements multiple times. Loops repeat a statement or sequence of statements multiple times. There are three loop types: There are three loop types: Basic loop Basic loop FOR loop FOR loop WHILE loop WHILE loop Loops repeat a statement or sequence of statements multiple times. Loops repeat a statement or sequence of statements multiple times. There are three loop types: There are three loop types: Basic loop Basic loop FOR loop FOR loop WHILE loop WHILE loop

62 Basic Loop Syntax Syntax LOOP statement1;... EXIT [WHEN condition]; END LOOP; LOOP statement1;... EXIT [WHEN condition]; END LOOP; where:conditionis a Boolean variable or expression (TRUE, FALSE, or NULL); where:conditionis a Boolean variable or expression (TRUE, FALSE, or NULL); -- delimiter -- statements -- EXIT statement -- delimiter

63 Basic Loop DECLARE v_ordiditem.ordid%TYPE := 601; v_counterNUMBER(2) := 1; BEGIN LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, v_counter); v_counter := v_counter + 1; EXIT WHEN v_counter > 10; END LOOP; END; DECLARE v_ordiditem.ordid%TYPE := 601; v_counterNUMBER(2) := 1; BEGIN LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, v_counter); v_counter := v_counter + 1; EXIT WHEN v_counter > 10; END LOOP; END; Example Example

64 FOR Loop Syntax Syntax Use a FOR loop to shortcut the test for the number of iterations. Use a FOR loop to shortcut the test for the number of iterations. Do not declare the counter; it is declared implicitly. Do not declare the counter; it is declared implicitly. Syntax Syntax Use a FOR loop to shortcut the test for the number of iterations. Use a FOR loop to shortcut the test for the number of iterations. Do not declare the counter; it is declared implicitly. Do not declare the counter; it is declared implicitly. FOR counter in [REVERSE] lower_bound..upper_bound LOOP statement1; statement2;... END LOOP; FOR counter in [REVERSE] lower_bound..upper_bound LOOP statement1; statement2;... END LOOP;

65 FOR Loop Guidelines Guidelines Reference the counter within the loop only; it is undefined outside the loop. Reference the counter within the loop only; it is undefined outside the loop. The lower and upper bounds of the loop could be values, variables, or expressions The lower and upper bounds of the loop could be values, variables, or expressions Do not reference the counter as the target of an assignment. An error message rises if you do so. Do not reference the counter as the target of an assignment. An error message rises if you do so. Guidelines Guidelines Reference the counter within the loop only; it is undefined outside the loop. Reference the counter within the loop only; it is undefined outside the loop. The lower and upper bounds of the loop could be values, variables, or expressions The lower and upper bounds of the loop could be values, variables, or expressions Do not reference the counter as the target of an assignment. An error message rises if you do so. Do not reference the counter as the target of an assignment. An error message rises if you do so.

66 FOR Loop Insert the first 10 new line items for order number 601. Insert the first 10 new line items for order number 601. Example Example Insert the first 10 new line items for order number 601. Insert the first 10 new line items for order number 601. Example Example DECLARE v_ordiditem.ordid%TYPE := 601; BEGIN FOR i IN 1..10 LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, i); END LOOP; END; DECLARE v_ordiditem.ordid%TYPE := 601; BEGIN FOR i IN 1..10 LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, i); END LOOP; END;

67 WHILE Loop Syntax Syntax Use the WHILE loop to repeat statements while a condition is TRUE. Use the WHILE loop to repeat statements while a condition is TRUE. Syntax Syntax Use the WHILE loop to repeat statements while a condition is TRUE. Use the WHILE loop to repeat statements while a condition is TRUE. WHILE condition LOOP statement1; statement2;... END LOOP; WHILE condition LOOP statement1; statement2;... END LOOP; Condition is evaluated at the beginning of each iteration.

68 WHILE Loop Example Example SQL>ACCEPT v_dept_name PROMPT 'Enter the dept. name: ' SQL>ACCEPT num_depts PROMPT 'Enter number of depts: ' SQL>DECLARE v_countNUMBER(2) := 1; BEGIN WHILE v_count <= &num_depts LOOP INSERT INTO dept(deptno,dname) VALUES ( v_count, &v_dept_name ); v_count := v_count + 1; END LOOP; COMMIT; END; / SQL>ACCEPT v_dept_name PROMPT 'Enter the dept. name: ' SQL>ACCEPT num_depts PROMPT 'Enter number of depts: ' SQL>DECLARE v_countNUMBER(2) := 1; BEGIN WHILE v_count <= &num_depts LOOP INSERT INTO dept(deptno,dname) VALUES ( v_count, &v_dept_name ); v_count := v_count + 1; END LOOP; COMMIT; END; /

69 Working with Composite Datatypes

70 Composite Datatypes Types: Types: PL/SQL RECORDS PL/SQL RECORDS PL/SQL TABLES PL/SQL TABLES Contain internal components Contain internal components Types: Types: PL/SQL RECORDS PL/SQL RECORDS PL/SQL TABLES PL/SQL TABLES Contain internal components Contain internal components

71 PL/SQL Records Must contain one or more components of any scalar, RECORD, or PL/SQL TABLE datatype, called fields Must contain one or more components of any scalar, RECORD, or PL/SQL TABLE datatype, called fields Are similar in structure to records in a 3GL Are similar in structure to records in a 3GL Are not the same as rows in a database table Are not the same as rows in a database table Treat a collection of fields as a logical unit Treat a collection of fields as a logical unit Are convenient for fetching a row of data from a table for processing Are convenient for fetching a row of data from a table for processing Must contain one or more components of any scalar, RECORD, or PL/SQL TABLE datatype, called fields Must contain one or more components of any scalar, RECORD, or PL/SQL TABLE datatype, called fields Are similar in structure to records in a 3GL Are similar in structure to records in a 3GL Are not the same as rows in a database table Are not the same as rows in a database table Treat a collection of fields as a logical unit Treat a collection of fields as a logical unit Are convenient for fetching a row of data from a table for processing Are convenient for fetching a row of data from a table for processing

72 Creating a PL/SQL Record Syntax Syntax Where field_declaration is Where field_declaration is Syntax Syntax Where field_declaration is Where field_declaration is TYPE type_name IS RECORD (field_declaration[, field_declaration] … ); identifiertype_name; TYPE type_name IS RECORD (field_declaration[, field_declaration] … ); identifiertype_name; field_name {field_type | variable%TYPE | table.column%TYPE | table%ROWTYPE} [[NOT NULL] {:= | DEFAULT} expr] field_name {field_type | variable%TYPE | table.column%TYPE | table%ROWTYPE} [[NOT NULL] {:= | DEFAULT} expr]

73 Creating a PL/SQL Record Declare variables to store the name, job, and salary of a new employee. Declare variables to store the name, job, and salary of a new employee. Example Example Declare variables to store the name, job, and salary of a new employee. Declare variables to store the name, job, and salary of a new employee. Example Example... TYPE emp_record_type IS RECORD (enameVARCHAR2(10), job VARCHAR2(9), salNUMBER(7,2)); emp_recordemp_record_type;... TYPE emp_record_type IS RECORD (enameVARCHAR2(10), job VARCHAR2(9), salNUMBER(7,2)); emp_recordemp_record_type;...

74 PL/SQL Record Structure Field1 (datatype) Field2 (datatype) Field3 (datatype) empno number(4) ename varchar2(10) job varchar2(9) Field1 (datatype) Field2 (datatype) Field3 (datatype) ExampleExample

75 The %ROWTYPE Attribute Declare a variable according to a collection of columns in a database table or view. Declare a variable according to a collection of columns in a database table or view. Prefix %ROWTYPE with the database table. Prefix %ROWTYPE with the database table. Fields in the record take their names and datatypes from the columns of the table or view. Fields in the record take their names and datatypes from the columns of the table or view. Declare a variable according to a collection of columns in a database table or view. Declare a variable according to a collection of columns in a database table or view. Prefix %ROWTYPE with the database table. Prefix %ROWTYPE with the database table. Fields in the record take their names and datatypes from the columns of the table or view. Fields in the record take their names and datatypes from the columns of the table or view.

76 The %ROWTYPE Attribute Examples Examples Declare a variable to store the same information about a department as it is stored in the DEPT table. Declare a variable to store the same information about a department as it is stored in the DEPT table. Declare a variable to store the same information about an employee as it is stored in the EMP table. Declare a variable to store the same information about an employee as it is stored in the EMP table. Examples Examples Declare a variable to store the same information about a department as it is stored in the DEPT table. Declare a variable to store the same information about a department as it is stored in the DEPT table. Declare a variable to store the same information about an employee as it is stored in the EMP table. Declare a variable to store the same information about an employee as it is stored in the EMP table. dept_recorddept%ROWTYPE; emp_recordemp%ROWTYPE;

77 %ROWTYPE Example SQL> SET SERVEROUTPUT ON; SQL> DECLARE d dept%ROWTYPE; d dept%ROWTYPE; BEGIN BEGIN SELECT deptno,dname,loc INTO d FROM dept WHERE deptno=10; SELECT deptno,dname,loc INTO d FROM dept WHERE deptno=10; DBMS_OUTPUT.PUT_LINE(d.dname); DBMS_OUTPUT.PUT_LINE(d.dname); END; END; /ACCOUNTING

78 PL/SQL Tables Are composed of two components: Are composed of two components: Primary key of datatype BINARY_INTEGER Primary key of datatype BINARY_INTEGER Column of scalar or record datatype Column of scalar or record datatype Increase dynamically because they are unconstrained Increase dynamically because they are unconstrained Are composed of two components: Are composed of two components: Primary key of datatype BINARY_INTEGER Primary key of datatype BINARY_INTEGER Column of scalar or record datatype Column of scalar or record datatype Increase dynamically because they are unconstrained Increase dynamically because they are unconstrained

79 Creating a PL/SQL Table Syntax Syntax TYPE type_name IS TABLE OF {column_type | variable%TYPE | table.column%TYPE} [NOT NULL] [INDEX BY BINARY_INTEGER]; identifiertype_name; TYPE type_name IS TABLE OF {column_type | variable%TYPE | table.column%TYPE} [NOT NULL] [INDEX BY BINARY_INTEGER]; identifiertype_name;... TYPE ename_table_type IS TABLE OF emp.ename%TYPE INDEX BY BINARY_INTEGER; ename_table ename_table_type;... TYPE ename_table_type IS TABLE OF emp.ename%TYPE INDEX BY BINARY_INTEGER; ename_table ename_table_type;... ExampleExample Declare a PL/SQL table to store names.

80 PL/SQL Table Structure Primary keyColumn Primary keyColumn............ 1Jones 1Jones 2Smith 2Smith 3Maduro 3Maduro............ BINARY_INTEGERScalar BINARY_INTEGERScalar

81 Tables Example SQL> DECLARE TYPE ename_table_type IS TABLE OF emp.ename%TYPE INDEX BY BINARY_INTEGER; TYPE ename_table_type IS TABLE OF emp.ename%TYPE INDEX BY BINARY_INTEGER; ename_table ename_table_type; ename_table ename_table_type; BEGIN BEGIN ename_table(2):='Mike'; ename_table(2):='Mike'; DBMS_OUTPUT.PUT_LINE(ename_table(2)); DBMS_OUTPUT.PUT_LINE(ename_table(2)); END; END; /Mike SQL> DECLARE TYPE ename_table_type IS TABLE OF emp.ename%TYPE INDEX BY BINARY_INTEGER; TYPE ename_table_type IS TABLE OF emp.ename%TYPE INDEX BY BINARY_INTEGER; ename_table ename_table_type; ename_table ename_table_type; BEGIN BEGIN ename_table(2):='Mike'; ename_table(2):='Mike'; DBMS_OUTPUT.PUT_LINE(ename_table(2)); DBMS_OUTPUT.PUT_LINE(ename_table(2)); END; END; /Mike

82 CursorsCursors

83 SQL Cursor A cursor is a private SQL work area. A cursor is a private SQL work area. There are two types of cursors: There are two types of cursors: Implicit cursors Implicit cursors Explicit cursors Explicit cursors The Oracle Server uses implicit cursors to parse and execute your SQL statements. The Oracle Server uses implicit cursors to parse and execute your SQL statements. Explicit cursors are explicitly declared by the programmer. Explicit cursors are explicitly declared by the programmer. A cursor is a private SQL work area. A cursor is a private SQL work area. There are two types of cursors: There are two types of cursors: Implicit cursors Implicit cursors Explicit cursors Explicit cursors The Oracle Server uses implicit cursors to parse and execute your SQL statements. The Oracle Server uses implicit cursors to parse and execute your SQL statements. Explicit cursors are explicitly declared by the programmer. Explicit cursors are explicitly declared by the programmer.

84 Cursor Context Area active set Number of rows processed Parsed command statement Database Server Memory

85 SQL Cursor Attributes Using SQL cursor attributes, you can test the outcome of your SQL statements. Using SQL cursor attributes, you can test the outcome of your SQL statements. SQL%ROWCOUNTNumber of rows affected by the most recent SQL statement (an integervalue) SQL%FOUNDBoolean attribute that evaluates to TRUE if the most recent SQL statement affects oneor more rows SQL%NOTFOUNDBoolean attribute that evaluates to TRUE if the most recent SQL statement does not affect any rows SQL%ISOPENAlways evaluates to FALSE because PL/SQL closes implicit cursors immediately after they are executed

86 SQL Cursor Attributes Delete rows that have the specified order number from the ITEM table. Print the number of rows deleted. Delete rows that have the specified order number from the ITEM table. Print the number of rows deleted. Example Example Delete rows that have the specified order number from the ITEM table. Print the number of rows deleted. Delete rows that have the specified order number from the ITEM table. Print the number of rows deleted. Example Example VARIABLE rows_deleted VARCHAR2(30) DECLARE v_ordid NUMBER := 605; BEGIN DELETE FROM item WHERE ordid = v_ordid; :rows_deleted := (SQL%ROWCOUNT || ' rows deleted.'); END; / PRINT rows_deleted

87 Implicit Cursor SQL%ROWCOUNT Example SQL> SET SERVEROUTPUT ON; SQL> DECLARE r NUMBER; r NUMBER; BEGIN BEGIN DELETE FROM emp WHERE empno=7900; DELETE FROM emp WHERE empno=7900; r:=SQL%ROWCOUNT; r:=SQL%ROWCOUNT; DBMS_OUTPUT.PUT_LINE(r); DBMS_OUTPUT.PUT_LINE(r); END; END; /1

88 Implicit Cursor SQL%FOUND Example SQL> DECLARE r BOOLEAN; r BOOLEAN; BEGIN BEGIN DELETE FROM emp WHERE empno=1000; DELETE FROM emp WHERE empno=1000; r:=SQL%FOUND; r:=SQL%FOUND; IF r THEN IF r THEN DBMS_OUTPUT.PUT_LINE('Rows are founded'); DBMS_OUTPUT.PUT_LINE('Rows are founded'); ELSE ELSE DBMS_OUTPUT.PUT_LINE('No Rows are founded'); DBMS_OUTPUT.PUT_LINE('No Rows are founded'); END IF; END IF; END; END; / No Rows are founded

89 Implicit Cursor SQL%ISOPEN Example SQL> DECLARE r BOOLEAN; r BOOLEAN; BEGIN BEGIN UPDATE emp SET sal=1000 WHERE empno>7900; UPDATE emp SET sal=1000 WHERE empno>7900; r:=SQL%ISOPEN; r:=SQL%ISOPEN; IF r THEN IF r THEN DBMS_OUTPUT.PUT_LINE('The cursor is opened'); DBMS_OUTPUT.PUT_LINE('The cursor is opened'); ELSE ELSE DBMS_OUTPUT.PUT_LINE('The cursor is closed'); DBMS_OUTPUT.PUT_LINE('The cursor is closed'); END IF; END IF; END; END; / The cursor is closed

90 About Cursors Every SQL statement executed by the Oracle Server has an individual cursor associated with it: Every SQL statement executed by the Oracle Server has an individual cursor associated with it: Implicit cursors: Declared for all DML and PL/SQL SELECT statements Implicit cursors: Declared for all DML and PL/SQL SELECT statements Explicit cursors: Declared and named by the programmer Explicit cursors: Declared and named by the programmer Every SQL statement executed by the Oracle Server has an individual cursor associated with it: Every SQL statement executed by the Oracle Server has an individual cursor associated with it: Implicit cursors: Declared for all DML and PL/SQL SELECT statements Implicit cursors: Declared for all DML and PL/SQL SELECT statements Explicit cursors: Declared and named by the programmer Explicit cursors: Declared and named by the programmer

91 Explicit Cursor Functions Active set Current row Cursor 7369SMITHCLERK 7566JONESMANAGER 7788SCOTTANALYST 7876ADAMSCLERK 7902FORDANALYST

92 Controlling Explicit Cursors Create a named SQL area Create a named SQL area DECLAREDECLARE Identify the active set Identify the active setOPENOPEN Load the current row into variables Load the current row into variablesFETCHFETCH Test for existing rows Test for existing rows EMPTY? Return to FETCH if rows found Return to FETCH if rows found No Release the active set Release the active setCLOSECLOSEYes

93 Controlling Explicit Cursors Open the cursor. Cursor Pointer Fetch a row from the cursor. Cursor Pointer Continue until empty. Cursor Pointer Close the cursor.

94 Explicit Cursor Example SQL> DECLARE v_num emp.empno%TYPE; v_num emp.empno%TYPE; v_name emp.ename%TYPE; v_name emp.ename%TYPE; CURSOR my_cursor IS SELECT empno,ename FROM emp WHERE empno>7900; CURSOR my_cursor IS SELECT empno,ename FROM emp WHERE empno>7900; BEGIN BEGIN OPEN my_cursor; OPEN my_cursor; LOOP LOOP FETCH my_cursor INTO v_num,v_name; FETCH my_cursor INTO v_num,v_name; EXIT WHEN my_cursor%NOTFOUND; EXIT WHEN my_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE(v_num || ' has the name ' ||v_name); DBMS_OUTPUT.PUT_LINE(v_num || ' has the name ' ||v_name); END LOOP; END LOOP; CLOSE my_cursor; CLOSE my_cursor; END; END; / 7902 has the name FORD 7934 has the name MILLER

95 Declaring the Cursor Syntax Syntax Do not include the INTO clause in the cursor declaration. Do not include the INTO clause in the cursor declaration. If processing rows in a specific sequence is required, use the ORDER BY clause in the query. If processing rows in a specific sequence is required, use the ORDER BY clause in the query. Syntax Syntax Do not include the INTO clause in the cursor declaration. Do not include the INTO clause in the cursor declaration. If processing rows in a specific sequence is required, use the ORDER BY clause in the query. If processing rows in a specific sequence is required, use the ORDER BY clause in the query. CURSOR cursor_name IS select_statement; CURSOR cursor_name IS select_statement;

96 Declaring the Cursor Example Example DECLARE CURSOR emp_cursor IS SELECT empno, ename FROM emp; CURSOR dept_cursor IS SELECT * FROM dept WHERE deptno = 10; BEGIN... DECLARE CURSOR emp_cursor IS SELECT empno, ename FROM emp; CURSOR dept_cursor IS SELECT * FROM dept WHERE deptno = 10; BEGIN...

97 Opening the Cursor Syntax Syntax Open the cursor to execute the query and identify the active set. Open the cursor to execute the query and identify the active set. If the query returns no rows, no exception is raised. If the query returns no rows, no exception is raised. Use cursor attributes to test the outcome after a fetch. Use cursor attributes to test the outcome after a fetch. Syntax Syntax Open the cursor to execute the query and identify the active set. Open the cursor to execute the query and identify the active set. If the query returns no rows, no exception is raised. If the query returns no rows, no exception is raised. Use cursor attributes to test the outcome after a fetch. Use cursor attributes to test the outcome after a fetch. OPENcursor_name;

98 Fetching Data from the Cursor Syntax Syntax Retrieve the current row values into variables. Retrieve the current row values into variables. Include the same number of variables. Include the same number of variables. Match each variable to correspond to the columns positionally. Match each variable to correspond to the columns positionally. Test to see if the cursor contains rows. Test to see if the cursor contains rows. Syntax Syntax Retrieve the current row values into variables. Retrieve the current row values into variables. Include the same number of variables. Include the same number of variables. Match each variable to correspond to the columns positionally. Match each variable to correspond to the columns positionally. Test to see if the cursor contains rows. Test to see if the cursor contains rows. FETCH cursor_name INTO[variable1, variable2,...] | record_name]; FETCH cursor_name INTO[variable1, variable2,...] | record_name];

99 Fetching Data from the Cursor Examples Examples Examples Examples FETCH emp_cursor INTO v_empno, v_ename;... OPEN defined_cursor; LOOP FETCH defined_cursor INTO defined_variables EXIT WHEN...;... -- Process the retrieved data... END;... OPEN defined_cursor; LOOP FETCH defined_cursor INTO defined_variables EXIT WHEN...;... -- Process the retrieved data... END;

100 Closing the Cursor Syntax Syntax Close the cursor after completing the processing of the rows. Close the cursor after completing the processing of the rows. Reopen the cursor, if required. Reopen the cursor, if required. Do not attempt to fetch data from a cursor once it has been closed. Do not attempt to fetch data from a cursor once it has been closed. Syntax Syntax Close the cursor after completing the processing of the rows. Close the cursor after completing the processing of the rows. Reopen the cursor, if required. Reopen the cursor, if required. Do not attempt to fetch data from a cursor once it has been closed. Do not attempt to fetch data from a cursor once it has been closed. CLOSEcursor_name;

101 Explicit Cursor Attributes Obtain status information about a cursor. Obtain status information about a cursor. AttributeType Description %ISOPENBoolean Evaluates to TRUE if the cursor is open %NOTFOUNDBoolean Evaluates to TRUE if the most recent fetch does not return a row %FOUNDBoolean Evaluates to TRUE if the most recent fetch returns a row; complement of %NOTFOUND %ROWCOUNTNumberEvaluates to the total number of rows returned so far

102 Controlling Multiple Fetches Process several rows from an explicit cursor using a loop. Process several rows from an explicit cursor using a loop. Fetch a row with each iteration. Fetch a row with each iteration. Use the %NOTFOUND attribute to write a test for an unsuccessful fetch. Use the %NOTFOUND attribute to write a test for an unsuccessful fetch. Use explicit cursor attributes to test the success of each fetch. Use explicit cursor attributes to test the success of each fetch. Process several rows from an explicit cursor using a loop. Process several rows from an explicit cursor using a loop. Fetch a row with each iteration. Fetch a row with each iteration. Use the %NOTFOUND attribute to write a test for an unsuccessful fetch. Use the %NOTFOUND attribute to write a test for an unsuccessful fetch. Use explicit cursor attributes to test the success of each fetch. Use explicit cursor attributes to test the success of each fetch.

103 The %ISOPEN Attribute Fetch rows only when the cursor is open. Fetch rows only when the cursor is open. Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor is open. Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor is open. Example Example Fetch rows only when the cursor is open. Fetch rows only when the cursor is open. Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor is open. Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor is open. Example Example IF NOT emp_cursor%ISOPEN THEN OPEN emp_cursor; END IF; LOOP FETCH emp_cursor... IF NOT emp_cursor%ISOPEN THEN OPEN emp_cursor; END IF; LOOP FETCH emp_cursor...

104 The %NOTFOUND and %ROWCOUNT Attributes Use the %ROWCOUNT cursor attribute to retrieve an exact number of rows. Use the %ROWCOUNT cursor attribute to retrieve an exact number of rows. The value of %ROWCOUNT before fetching any row is NULL. The value of %ROWCOUNT before fetching any row is NULL. Use the %NOTFOUND cursor attribute to determine when to exit the loop. Use the %NOTFOUND cursor attribute to determine when to exit the loop. Use the %ROWCOUNT cursor attribute to retrieve an exact number of rows. Use the %ROWCOUNT cursor attribute to retrieve an exact number of rows. The value of %ROWCOUNT before fetching any row is NULL. The value of %ROWCOUNT before fetching any row is NULL. Use the %NOTFOUND cursor attribute to determine when to exit the loop. Use the %NOTFOUND cursor attribute to determine when to exit the loop.

105 Explicit Cursor %ISOPEN Example SQL> DECLARE v_num emp.empno%TYPE; v_num emp.empno%TYPE; v_name emp.ename%TYPE; v_name emp.ename%TYPE; r BOOLEAN; r BOOLEAN; CURSOR my_cursor IS SELECT empno,ename FROM emp WHERE empno>7900; CURSOR my_cursor IS SELECT empno,ename FROM emp WHERE empno>7900; BEGIN BEGIN OPEN my_cursor; OPEN my_cursor; r:=my_cursor%ISOPEN; r:=my_cursor%ISOPEN; IF r THEN IF r THEN DBMS_OUTPUT.PUT_LINE('The Cursor is opened after the open statement'); DBMS_OUTPUT.PUT_LINE('The Cursor is opened after the open statement'); ELSE ELSE DBMS_OUTPUT.PUT_LINE('The Cursor is closed after the open statement'); DBMS_OUTPUT.PUT_LINE('The Cursor is closed after the open statement'); END IF; END IF;

106 Explicit Cursor %ISOPEN Example Cont. LOOP FETCH my_cursor INTO v_num,v_name; FETCH my_cursor INTO v_num,v_name; EXIT WHEN my_cursor%NOTFOUND; EXIT WHEN my_cursor%NOTFOUND; END LOOP; END LOOP; CLOSE my_cursor; CLOSE my_cursor; r:=my_cursor%ISOPEN; r:=my_cursor%ISOPEN; IF r THEN IF r THEN DBMS_OUTPUT.PUT_LINE('The Cursor is opened after the close statement'); DBMS_OUTPUT.PUT_LINE('The Cursor is opened after the close statement'); ELSE ELSE DBMS_OUTPUT.PUT_LINE('The Cursor is closed after the close statement'); DBMS_OUTPUT.PUT_LINE('The Cursor is closed after the close statement'); END IF; END IF; END; END; / The Cursor is opened after the open statement The Cursor is closed after the close statement

107 Explicit Cursor %ROWCOUNT Example SQL> DECLARE v_name emp.ename%TYPE; v_name emp.ename%TYPE; r NUMBER; r NUMBER; c NUMBER:=1; c NUMBER:=1; CURSOR my_cursor IS SELECT ename FROM emp WHERE empno>7900; CURSOR my_cursor IS SELECT ename FROM emp WHERE empno>7900; BEGIN BEGIN OPEN my_cursor; OPEN my_cursor; LOOP LOOP FETCH my_cursor INTO v_name; FETCH my_cursor INTO v_name; EXIT WHEN my_cursor%NOTFOUND; EXIT WHEN my_cursor%NOTFOUND; r:=my_cursor%ROWCOUNT; r:=my_cursor%ROWCOUNT; DBMS_OUTPUT.PUT_LINE('After fetch number ' || c || ' ROWCOUNT has the value ' || r); DBMS_OUTPUT.PUT_LINE('After fetch number ' || c || ' ROWCOUNT has the value ' || r); c:=c+1; c:=c+1; END LOOP; END LOOP; CLOSE my_cursor; CLOSE my_cursor; END; END; / After fetch number 1 ROWCOUNT has the value 1 After fetch number 2 ROWCOUNT has the value 2

108 Cursors and Records Process the rows of the active set conveniently by fetching values into a PL/SQL RECORD. Process the rows of the active set conveniently by fetching values into a PL/SQL RECORD. Example Example Process the rows of the active set conveniently by fetching values into a PL/SQL RECORD. Process the rows of the active set conveniently by fetching values into a PL/SQL RECORD. Example Example DECLARE CURSOR emp_cursor IS SELECTempno, ename FROMemp; emp_recordemp_cursor%ROWTYPE; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO emp_record;... DECLARE CURSOR emp_cursor IS SELECTempno, ename FROMemp; emp_recordemp_cursor%ROWTYPE; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO emp_record;...

109 Syntax Syntax The cursor FOR loop is a shortcut to process explicit cursors. The cursor FOR loop is a shortcut to process explicit cursors. Implicit open, fetch, and close occur. Implicit open, fetch, and close occur. The record is implicitly declared. The record is implicitly declared. Syntax Syntax The cursor FOR loop is a shortcut to process explicit cursors. The cursor FOR loop is a shortcut to process explicit cursors. Implicit open, fetch, and close occur. Implicit open, fetch, and close occur. The record is implicitly declared. The record is implicitly declared. Cursor FOR Loops FOR record_name IN cursor_name LOOP statement1; statement2;... END LOOP; FOR record_name IN cursor_name LOOP statement1; statement2;... END LOOP;

110 Cursor FOR Loops Retrieve employees one by one until no more are left. Retrieve employees one by one until no more are left. Example Example Retrieve employees one by one until no more are left. Retrieve employees one by one until no more are left. Example Example DECLARE CURSOR emp_cursor IS SELECT ename, deptno FROM emp; BEGIN FOR emp_record IN emp_cursor LOOP -- implicit open and implicit fetch occur IF emp_record.deptno = 30 THEN... END LOOP; -- implicit close occurs END; DECLARE CURSOR emp_cursor IS SELECT ename, deptno FROM emp; BEGIN FOR emp_record IN emp_cursor LOOP -- implicit open and implicit fetch occur IF emp_record.deptno = 30 THEN... END LOOP; -- implicit close occurs END;

111 Handling Exceptions

112 Handling Exceptions with PL/SQL What is an exception? Identifier in PL/SQL that is raised during execution What is an exception? Identifier in PL/SQL that is raised during execution How is it raised? How is it raised? An Oracle error occurs. An Oracle error occurs. You raise it explicitly. You raise it explicitly. How do you handle it? How do you handle it? Trap it with a handler. Trap it with a handler. What is an exception? Identifier in PL/SQL that is raised during execution What is an exception? Identifier in PL/SQL that is raised during execution How is it raised? How is it raised? An Oracle error occurs. An Oracle error occurs. You raise it explicitly. You raise it explicitly. How do you handle it? How do you handle it? Trap it with a handler. Trap it with a handler.

113 Handling Exceptions Trap the exception Trap the exception DECLARE BEGIN END; Exception is raised EXCEPTION Exception is trapped

114 Exception Types Predefined Oracle Server Predefined Oracle Server Non-predefined Oracle Server Non-predefined Oracle Server User-defined User-defined Predefined Oracle Server Predefined Oracle Server Non-predefined Oracle Server Non-predefined Oracle Server User-defined User-defined} Implicitly raised Explicitly raised

115 Trapping Exceptions EXCEPTION WHEN exception1 [OR exception2...] THEN statement1; statement2;... [WHEN exception3 [OR exception4...] THEN statement1; statement2;...] [WHEN OTHERS THEN statement1; statement2;...] EXCEPTION WHEN exception1 [OR exception2...] THEN statement1; statement2;... [WHEN exception3 [OR exception4...] THEN statement1; statement2;...] [WHEN OTHERS THEN statement1; statement2;...] Syntax Syntax

116 Trapping Exceptions Guidelines WHEN OTHERS is the last clause. WHEN OTHERS is the last clause. EXCEPTION keyword starts exception- handling section. EXCEPTION keyword starts exception- handling section. Several exception handlers are allowed. Several exception handlers are allowed. Only one handler is processed before leaving the block. Only one handler is processed before leaving the block. WHEN OTHERS is the last clause. WHEN OTHERS is the last clause. EXCEPTION keyword starts exception- handling section. EXCEPTION keyword starts exception- handling section. Several exception handlers are allowed. Several exception handlers are allowed. Only one handler is processed before leaving the block. Only one handler is processed before leaving the block.

117 Trapping Predefined Oracle Server Errors  Common errors that have been given predefined names Reference the standard name in the exception- handling routine. Reference the standard name in the exception- handling routine. Sample predefined exceptions: Sample predefined exceptions:  Common errors that have been given predefined names Reference the standard name in the exception- handling routine. Reference the standard name in the exception- handling routine. Sample predefined exceptions: Sample predefined exceptions:

118 Predefined Exception BEGIN EXCEPTION WHEN NO_DATA_FOUND THEN statement1; statement2; WHEN TOO_MANY_ROWS THEN statement1; WHEN OTHERS THEN statement1; statement2; statement3; END; Syntax Syntax

119 Trapping Non-Predefined Oracle Server Errors Declare Name the exception Name the exception Associate Code the PRAGMA EXCEPTION_INIT Code the PRAGMA EXCEPTION_INIT Declarative section Reference Handle the raised exception Handle the raised exception Exception-handlingsection Less-common errors that have not been given predefined names

120 DECLARE e_emps_remainingEXCEPTION; PRAGMA EXCEPTION_INIT ( e_emps_remaining, -2292); v_deptno dept.deptno%TYPE := &p_deptno; BEGIN DELETE FROM dept WHERE deptno = v_deptno; COMMIT; EXCEPTION WHEN e_emps_remaining THEN DBMS_OUTPUT.PUT_LINE ('Cannot remove dept ' || TO_CHAR(v_deptno) || '. Employees exist. '); END; DECLARE e_emps_remainingEXCEPTION; PRAGMA EXCEPTION_INIT ( e_emps_remaining, -2292); v_deptno dept.deptno%TYPE := &p_deptno; BEGIN DELETE FROM dept WHERE deptno = v_deptno; COMMIT; EXCEPTION WHEN e_emps_remaining THEN DBMS_OUTPUT.PUT_LINE ('Cannot remove dept ' || TO_CHAR(v_deptno) || '. Employees exist. '); END; Non-Predefined Error Trap for Oracle Server error number 2292, an integrity constraint violation. Trap for Oracle Server error number –2292, an integrity constraint violation. e_emps_remaining EXCEPTION; 1 PRAGMA EXCEPTION_INIT ( e_emps_remaining, -2292); 2 e_emps_remaining 3

121 Functions for Trapping Exceptions SQLCODE Returns the numeric value for the error code SQLCODE Returns the numeric value for the error code SQLERRM Returns the message associated with the error number SQLERRM Returns the message associated with the error number SQLCODE Returns the numeric value for the error code SQLCODE Returns the numeric value for the error code SQLERRM Returns the message associated with the error number SQLERRM Returns the message associated with the error number

122 Functions for Trapping Exceptions DECLARE v_error_code NUMBER; v_error_message VARCHAR2(255); BEGIN... EXCEPTION... WHEN OTHERS THEN ROLLBACK; v_error_code := SQLCODE ; v_error_message := SQLERRM ; INSERT INTO errors VALUES(v_error_code, v_error_message); END; Example Example SQLCODE SQLERRM

123 Trapping User-Defined Exceptions Name the exception Name the exception Declare Declarativesection Raise Explicitly raise the exception by using the RAISE statement Explicitly raise the exception by using the RAISE statement Executablesection Reference Handle the raised exception Handle the raised exception Exception-handlingsection

124 User-Defined Exception DECLARE e_invalid_product EXCEPTION; BEGIN UPDATEproduct SETdescrip = '&product_description' WHEREprodid = &product_number; IF SQL%NOTFOUND THEN RAISE e_invalid_product; END IF; COMMIT; EXCEPTION WHEN e_invalid_product THEN DBMS_OUTPUT.PUT_LINE('Invalid product number.'); END; ExampleExample e_invalid_product EXCEPTION; 1 RAISE e_invalid_product; 2 e_invalid_product 3

125 RAISE_APPLICATION_ERROR Procedure Syntax Syntax A procedure that lets you issue user-defined error messages from stored subprograms A procedure that lets you issue user-defined error messages from stored subprograms Called only from an executing stored subprogram Called only from an executing stored subprogram Syntax Syntax A procedure that lets you issue user-defined error messages from stored subprograms A procedure that lets you issue user-defined error messages from stored subprograms Called only from an executing stored subprogram Called only from an executing stored subprogram raise_application_error (error_number, message[, {TRUE | FALSE}]);

126 RAISE_APPLICATION_ERROR Example …EXCEPTION WHEN NO_DATA_FOUND THEN RAISE_APPLICATION_ERROR(-20201, 'Invalid Number'); RAISE_APPLICATION_ERROR(-20201, 'Invalid Number');END;…EXCEPTION WHEN NO_DATA_FOUND THEN RAISE_APPLICATION_ERROR(-20201, 'Invalid Number'); RAISE_APPLICATION_ERROR(-20201, 'Invalid Number');END;


Download ppt "PL/SQLPL/SQL Declaring Variables Declaring Variables Declaring Variables Declaring Variables Writing Executable Statements Writing Executable Statements."

Similar presentations


Ads by Google