Download presentation
Presentation is loading. Please wait.
Published bySabina Austin Modified over 9 years ago
1
Introduction to PL/SQL
2
Objectives After completing this lesson, you should be able to do the following: Explain the need for PL/SQL Explain the benefits of PL/SQL Identify the different types of PL/SQL blocks Output messages in PL/SQL
3
About PL/SQL PL/SQL: Stands for “Procedural Language extension to SQL” Is Oracle Corporation’s standard data access language for relational databases Seamlessly integrates procedural constructs with SQL
4
About PL/SQL PL/SQL: Provides a block structure for executable units of code. Maintenance of code is made easier with such a well-defined structure. Provides procedural constructs such as: Variables, constants, and data types Control structures such as conditional statements and loops Reusable program units that are written once and executed many times
5
PL/SQL Environment PL/SQL engine Oracle database server SQL statement executor Procedural statement executor procedural SQL PL/SQL block
6
Benefits of PL/SQL Integration of procedural constructs with SQL Improved performance SQL IF...THEN SQL ELSE SQL END IF; SQL SQL 1 SQL 2 …
7
Benefits of PL/SQL Modularized program development Integration with Oracle tools Portability Exception handling
9
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)
11
Block Types Anonymous Procedure Function [DECLARE] BEGIN --statements [EXCEPTION] END; PROCEDURE name IS BEGIN --statements [EXCEPTION] END; FUNCTION name RETURN datatype IS BEGIN --statements RETURN value; [EXCEPTION] END;
13
Program Constructs Application triggers Application packages Application procedures or functions Anonymous blocks Tools Constructs Object types Database triggers Stored packages Stored procedures or functions Anonymous blocks Database Server Constructs Object types
15
Create an Anonymous Block Enter the anonymous block in the SQL Developer workspace:
16
Execute an Anonymous Block Click the Run Script button to execute the anonymous block: Run Script
17
Test the Output of a PL/SQL Block Enable output in SQL Developer by clicking the Enable DBMS Output button on the DBMS Output tab: Use a predefined Oracle package and its procedure: DBMS_OUTPUT.PUT_LINE DBMS_OUTPUT.PUT_LINE( ' The First Name of the Employee is ' || f_name); … Enable DBMS Output DBMS Output Tab
18
Test the Output of a PL/SQL Block
19
Declaring PL/SQL Variables
20
Objectives After completing this lesson, you should be able to do the following: Recognize valid and invalid identifiers List the uses of variables Declare and initialize variables List and describe various data types Identify the benefits of using the %TYPE attribute Declare, use, and print bind variables
21
Use of Variables Variables can be used for: Temporary storage of data Manipulation of stored values Reusability SELECT first_name, department_id INTO v_fname, v_deptno FROM … v_fname v_deptno Jennifer 10
22
Requirements for Variable Names A variable name: Must start with a letter Can include letters or numbers Can include special characters (such as $, _, and # ) Must contain no more than 30 characters Must not include reserved words
23
Handling Variables in PL/SQL Variables are: Declared and initialized in the declarative section Used and assigned new values in the executable section Passed as parameters to PL/SQL subprograms Used to hold the output of a PL/SQL subprogram
24
Declaring and Initializing PL/SQL Variables Syntax: Examples: identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr]; DECLARE v_hiredateDATE; v_deptnoNUMBER(2) NOT NULL := 10; v_location VARCHAR2(13) := 'Atlanta'; c_commCONSTANT NUMBER := 1400;
25
Declaring and Initializing PL/SQL Variables DECLARE v_myName VARCHAR2(20); BEGIN DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName); v_myName := 'John'; DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName); END; / DECLARE v_myName VARCHAR2(20):= 'John'; BEGIN v_myName := 'Steven'; DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName); END; / 1 2
26
Delimiters in String Literals DECLARE v_event VARCHAR2(15); BEGIN v_event := q'!Father's day!'; DBMS_OUTPUT.PUT_LINE('3rd Sunday in June is : '|| v_event ); v_event := q'[Mother's day]'; DBMS_OUTPUT.PUT_LINE('2nd Sunday in May is : '|| v_event ); END; /
27
Types of Variables PL/SQL variables: Scalar Composite Reference Large object (LOB) Non-PL/SQL variables: Bind variables
28
TRUE Types of Variables 25-JAN-01 Atlanta 256120.08 Snow White Long, long ago, in a land far, far away, there lived a princess called Snow White...
29
Guidelines for Declaring and Initializing PL/SQL Variables Follow naming conventions. Use meaningful identifiers for variables. Initialize variables designated as NOT NULL and CONSTANT. Initialize variables with the assignment operator (:=) or the DEFAULT keyword: Declare one identifier per line for better readability and code maintenance. v_myName VARCHAR2(20):='John'; v_myName VARCHAR2(20) DEFAULT 'John';
30
Guidelines for Declaring PL/SQL Variables Avoid using column names as identifiers. Use the NOT NULL constraint when the variable must hold a value. DECLARE employee_idNUMBER(6); BEGIN SELECT employee_id INTOemployee_id FROMemployees WHERE last_name = 'Kochhar'; END; /
31
Scalar Data Types Hold a single value Have no internal components Atlanta TRUE 25-JAN-01 256120.08 The soul of the lazy man desires, and he has nothing; but the soul of the diligent shall be made rich.
32
Base Scalar Data Types CHAR [(maximum_length)] VARCHAR2 (maximum_length) NUMBER [(precision, scale)] BINARY_INTEGER PLS_INTEGER BOOLEAN BINARY_FLOAT BINARY_DOUBLE
34
Base Scalar Data Types DATE TIMESTAMP TIMESTAMP WITH TIME ZONE TIMESTAMP WITH LOCAL TIME ZONE INTERVAL YEAR TO MONTH INTERVAL DAY TO SECOND
36
Declaring Scalar Variables Examples: DECLARE v_emp_jobVARCHAR2(9); v_count_loop BINARY_INTEGER := 0; v_dept_total_salNUMBER(9,2) := 0; v_orderdate DATE := SYSDATE + 7; c_tax_rateCONSTANT NUMBER(3,2) := 8.25; v_valid BOOLEAN NOT NULL := TRUE;...
37
%TYPE Attribute Is used to declare a variable according to: A database column definition Another declared variable Is prefixed with: The database table and column The name of the declared variable
39
Declaring Variables with the %TYPE Attribute Syntax Examples... emp_lname employees.last_name%TYPE;... identifiertable.column_name%TYPE;... balance NUMBER(7,2); min_balance balance%TYPE := 1000;...
40
Declaring Boolean Variables Only the TRUE, FALSE, and NULL values can be assigned to a Boolean variable. Conditional expressions use the logical operators AND and OR and the unary operator NOT to check the variable values. The variables always yield TRUE, FALSE, or NULL. Arithmetic, character, and date expressions can be used to return a Boolean value.
41
Bind Variables Bind variables are: Created in the environment Also called host variables Created with the VARIABLE keyword Used in SQL statements and PL/SQL blocks Accessed even after the PL/SQL block is executed Referenced with a preceding colon
43
Printing Bind Variables Example: VARIABLE b_emp_salary NUMBER BEGIN SELECT salary INTO :b_emp_salary FROM employees WHERE employee_id = 178; END; / PRINT b_emp_salary SELECT first_name, last_name FROM employees WHERE salary=:b_emp_salary;
44
Printing Bind Variables Example: VARIABLE b_emp_salary NUMBER SET AUTOPRINT ON DECLARE v_empno NUMBER(6):=&empno; BEGIN SELECT salary INTO :b_emp_salary FROM employees WHERE employee_id = v_empno; END; 7000 Output:
45
LOB Data Type Variables Book ( CLOB ) Photo ( BLOB ) Movie ( BFILE ) NCLOB
46
Composite Data Types TRUE 23-DEC-98ATLANTA 15000 22345 312 43456 1SMITH 2JONES 3NANCY 4TIM PL/SQL table structure PLS_INTEGER VARCHAR2 PLS_INTEGER NUMBER
47
Writing Executable Statements
48
Objectives After completing this lesson, you should be able to do the following: Identify lexical units in a PL/SQL block Use built-in SQL functions in PL/SQL Describe when implicit conversions take place and when explicit conversions have to be dealt with Write nested blocks and qualify variables with labels Write readable code with appropriate indentation Use sequences in PL/SQL expressions
49
Lexical Units in a PL/SQL Block Lexical units: Are building blocks of any PL/SQL block Are sequences of characters including letters, numerals, tabs, spaces, returns, and symbols Can be classified as: Identifiers: v_fname, c_percent Delimiters: ;, +, - Literals: John, 428, True Comments: --, /* */
51
PL/SQL Block Syntax and Guidelines Literals Character and date literals must be enclosed in single quotation marks. Numbers can be simple values or in scientific notation. Statements can span several lines. name := 'Henderson'; 1 2 3
52
Commenting Code Prefix single-line comments with two hyphens ( -- ). Place multiple-line comments between the symbols /* and */. Example: DECLARE... v_annual_sal NUMBER (9,2); BEGIN /* Compute the annual salary based on the monthly salary input from the user */ v_annual_sal := monthly_sal * 12; --The following line displays the annual salary DBMS_OUTPUT.PUT_LINE(v_annual_sal); END; /
53
SQL Functions in PL/SQL Available in procedural statements: Single-row functions Not available in procedural statements: DECODE Group functions
54
SQL Functions in PL/SQL: Examples Get the length of a string: Get the number of months an employee has worked: v_desc_size INTEGER(5); v_prod_description VARCHAR2(70):='You can use this product with your radios for higher frequency'; -- get the length of the string in prod_description v_desc_size:= LENGTH(prod_description); v_tenure:= MONTHS_BETWEEN (CURRENT_DATE, v_hiredate);
55
Using Sequences in PL/SQL Expressions Starting in 11g: Before 11g: DECLARE v_new_id NUMBER; BEGIN SELECT my_seq.NEXTVAL INTO v_new_id FROM Dual; END; / DECLARE v_new_id NUMBER; BEGIN v_new_id := my_seq.NEXTVAL; END; /
56
Data Type Conversion Converts data to comparable data types Is of two types: Implicit conversion Explicit conversion Functions: TO_CHAR TO_DATE TO_NUMBER TO_TIMESTAMP
58
Data Type Conversion date_of_joining DATE:= '02-Feb-2000'; date_of_joining DATE:= 'February 02,2000'; date_of_joining DATE:= TO_DATE('February 02,2000','Month DD, YYYY'); 1 2 3
59
Nested Blocks PL/SQL blocks can be nested. An executable section ( BEGIN … END ) can contain nested blocks. An exception section can contain nested blocks.
60
Nested Blocks Example: DECLARE v_outer_variable VARCHAR2(20):='GLOBAL VARIABLE'; BEGIN DECLARE v_inner_variable VARCHAR2(20):='LOCAL VARIABLE'; BEGIN DBMS_OUTPUT.PUT_LINE(v_inner_variable); DBMS_OUTPUT.PUT_LINE(v_outer_variable); END; DBMS_OUTPUT.PUT_LINE(v_outer_variable); END;
61
Variable Scope and Visibility DECLARE v_father_name VARCHAR2(20):='Patrick'; v_date_of_birth DATE:='20-Apr-1972'; BEGIN DECLARE v_child_name VARCHAR2(20):='Mike'; v_date_of_birth DATE:='12-Dec-2002'; BEGIN DBMS_OUTPUT.PUT_LINE('Father''s Name: '||v_father_name); DBMS_OUTPUT.PUT_LINE('Date of Birth: '||v_date_of_birth); DBMS_OUTPUT.PUT_LINE('Child''s Name: '||v_child_name); END; DBMS_OUTPUT.PUT_LINE('Date of Birth: '||v_date_of_birth); END; / 1 2
63
Qualify an Identifier BEGIN > DECLARE v_father_name VARCHAR2(20):='Patrick'; v_date_of_birth DATE:='20-Apr-1972'; BEGIN DECLARE v_child_name VARCHAR2(20):='Mike'; v_date_of_birth DATE:='12-Dec-2002'; BEGIN DBMS_OUTPUT.PUT_LINE('Father''s Name: '||v_father_name); DBMS_OUTPUT.PUT_LINE('Date of Birth: ' ||outer.v_date_of_birth); DBMS_OUTPUT.PUT_LINE('Child''s Name: '||v_child_name); DBMS_OUTPUT.PUT_LINE('Date of Birth: '||v_date_of_birth); END; END outer;
64
Quiz: Determining Variable Scope BEGIN > DECLARE v_sal NUMBER(7,2) := 60000; v_comm NUMBER(7,2) := v_sal * 0.20; v_message VARCHAR2(255) := ' eligible for commission'; BEGIN DECLARE v_sal NUMBER(7,2) := 50000; v_comm NUMBER(7,2) := 0; v_total_comp NUMBER(7,2) := v_sal + v_comm; BEGIN v_message := 'CLERK not'||v_message; outer.v_comm := v_sal * 0.30; END; v_message := 'SALESMAN'||v_message; END; END outer; / 1 2
66
Operators in PL/SQL Logical Arithmetic Concatenation Parentheses to control order of operations Exponential operator (**) Same as in SQL }
67
Operators in PL/SQL: Examples Increment the counter for a loop. Set the value of a Boolean flag. Validate whether an employee number contains a value. loop_count := loop_count + 1; good_sal := sal BETWEEN 50000 AND 150000; valid:= (empno IS NOT NULL);
68
Programming Guidelines Make code maintenance easier by: Documenting code with comments Developing a case convention for the code Developing naming conventions for identifiers and other objects Enhancing readability by indenting
69
Indenting Code For clarity, indent each level of code. BEGIN IF x=0 THEN y:=1; END IF; END; / DECLARE deptno NUMBER(4); location_id NUMBER(4); BEGIN SELECTdepartment_id, location_id INTOdeptno, location_id FROMdepartments WHEREdepartment_name = 'Sales';... END; /
70
Interacting with the Oracle Database Server
71
Objectives After completing this lesson, you should be able to do the following: Determine the SQL statements that can be directly included in a PL/SQL executable block Manipulate data with DML statements in PL/SQL Use transaction control statements in PL/SQL Make use of the INTO clause to hold the values returned by a SQL statement Differentiate between implicit cursors and explicit cursors Use SQL cursor attributes
72
SQL Statements in PL/SQL Retrieve a row from the database by using the SELECT command. Make changes to rows in the database by using DML commands. Control a transaction with the COMMIT, ROLLBACK, or SAVEPOINT command.
73
SELECT Statements in PL/SQL Retrieve data from the database with a SELECT statement. Syntax: SELECT select_list INTO {variable_name[, variable_name]... | record_name} FROM table [WHERE condition];
75
SELECT Statements in PL/SQL The INTO clause is required. Queries must return only one row. Example: DECLARE v_fname VARCHAR2(25); BEGIN SELECT first_name INTO v_fname FROM employees WHERE employee_id=200; DBMS_OUTPUT.PUT_LINE(' First Name is : '||v_fname); END; /
77
Retrieving Data in PL/SQL Retrieve hire_date and salary for the specified employee. Example: DECLARE v_emp_hiredate employees.hire_date%TYPE; v_emp_salary employees.salary%TYPE; BEGIN SELECT hire_date, salary INTO v_emp_hiredate, v_emp_salary FROM employees WHERE employee_id = 100; END; /
78
DECLARE v_sum_sal NUMBER(10,2); v_deptno NUMBER NOT NULL := 60; BEGIN SELECTSUM(salary) -- group function INTO v_sum_sal FROMemployees WHERE department_id = v_deptno; DBMS_OUTPUT.PUT_LINE ('The sum of salary is ' || v_sum_sal); END; Retrieving Data in PL/SQL Return the sum of the salaries for all the employees in the specified department. Example:
79
Naming Conventions DECLARE hire_date employees.hire_date%TYPE; sysdate hire_date%TYPE; employee_id employees.employee_id%TYPE := 176; BEGIN SELECT hire_date, sysdate INTO hire_date, sysdate FROM employees WHERE employee_id = employee_id; END; /
80
Naming Conventions Use a naming convention to avoid ambiguity in the WHERE clause. Avoid using database column names as identifiers. Syntax errors can arise because PL/SQL checks the database first for a column in the table. The names of local variables and formal parameters take precedence over the names of database tables. The names of database table columns take precedence over the names of local variables.
81
Using PL/SQL to Manipulate Data Make changes to database tables by using DML commands: INSERT UPDATE DELETE MERGE INSERT UPDATE DELETE MERGE
82
Inserting Data Add new employee information to the EMPLOYEES table. Example: BEGIN INSERT INTO employees (employee_id, first_name, last_name, email, hire_date, job_id, salary) VALUES(employees_seq.NEXTVAL, 'Ruth', 'Cores', 'RCORES',CURRENT_DATE, 'AD_ASST', 4000); END; /
83
Updating Data Increase the salary of all employees who are stock clerks. Example: DECLARE sal_increase employees.salary%TYPE := 800; BEGIN UPDATEemployees SETsalary = salary + sal_increase WHEREjob_id = 'ST_CLERK'; END; /
84
Deleting Data Delete rows that belong to department 10 from the employees table. Example: DECLARE deptno employees.department_id%TYPE := 10; BEGIN DELETE FROM employees WHERE department_id = deptno; END; /
85
Merging Rows Insert or update rows in the copy_emp table to match the employees table. BEGIN MERGE INTO copy_emp c USING employees e ON (e.employee_id = c.empno) WHEN MATCHED THEN UPDATE SET c.first_name = e.first_name, c.last_name = e.last_name, c.email = e.email,... WHEN NOT MATCHED THEN INSERT VALUES(e.employee_id, e.first_name, e.last_name,...,e.department_id); END; /
87
SQL Cursor A cursor is a pointer to the private memory area allocated by the Oracle server. A cursor is used to handle the result set of a SELECT statement. There are two types of cursors: Implicit: Created and managed internally by the Oracle server to process SQL statements Explicit: Declared explicitly by the programmer
89
SQL Cursor Attributes for Implicit Cursors Using SQL cursor attributes, you can test the outcome of your SQL statements. SQL%FOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement returned at least one row SQL%NOTFO UND Boolean attribute that evaluates to TRUE if the most recent SQL statement did not return even one row SQL%ROWCO UNT An integer value that represents the number of rows affected by the most recent SQL statement
90
SQL Cursor Attributes for Implicit Cursors Delete rows that have the specified employee ID from the employees table. Print the number of rows deleted. Example: DECLARE v_rows_deleted VARCHAR2(30) v_empno employees.employee_id%TYPE := 176; BEGIN DELETE FROM employees WHERE employee_id = v_empno; v_rows_deleted := (SQL%ROWCOUNT || ' row deleted.'); DBMS_OUTPUT.PUT_LINE (v_rows_deleted); END;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.