PL/SQL Tutorial: Doan Quang Minh April 10, 2012 CTI Cosatech VN
PL/SQL Tutorial: Doan Quang Minh April 10, 2012 CTI Cosatech VN
I. Introduction (5 minutes)
II. Basic syntax (15 minutes)
III. Advanced syntax (30 minutes)
IV. Conclusion (2 minutes)
V. Reference (2 minutes)
VI. Keywords (3 minutes)
VII. Q&A
I. Introduction
4
1. Introduction to PL/SQL
What is PL/SQL?
The PL/SQL Engine
2. Advantages of PL/SQL
Block Structures
Procedural Language Capability
Better Performance
Error Handling
1. Introduction to PL/SQL
5
What is PL/SQL?
Procedural Language extension of SQL.
PL/SQL is a combination of SQL along with the
procedural features of programming languages. It
was developed by Oracle Corporation in the early
90’s to enhance the capabilities of SQL.
I. Introduction
1. Introduction to PL/SQL(cont)
6
I. Introduction
2. Advantages of PL/SQL
7
I. Introduction
2. Advantages of PL/SQL(cont)
8
I. Introduction
II. Basic syntax
9
1. Block Structures
2. Operators
3. Comments
4. Delimiters
5. Variables
6. Constants
7. Records
8. Conditional Statements
9. Iterative Statements
1. Block Structures
10
Comparison operators
NOT IS NULL LIKE BETWEEN IN AND OR
+ - * / @ ; = <> != || <= >=
Assignment operator
:= (You can assign values to a variable, literal value, or function call
but NOT a table column)
Comment
-- comment
/* comment */
Example
DECLARE
/* Multi-line comments are not required to actually use
multiple lines. */
BEGIN
-- This is a single line comment
NULL;
END;
Delimiter
Item separator .
Character string delimiter '
Quoted String delimiter "
Bind variable indicator :
Attribute indicator %
Statement terminator ;
Example
job_record.jobname := 'Test Job';
v_empno emp.empno%TYPE := &empno;
Variable
variable_name datatype [NOT NULL := value ];
Example
DECLARE
v_first_name VARCHAR2(20);
v_employee_id NUMBER NOT NULL;
v_last_name EMPLOYEES.LAST_NAME%TYPE;
v_employee EMPLOYEES%ROWTYPE;
v_hire_date DATE;
BEGIN
NULL;
END;
Constant
constant_name CONSTANT datatype := VALUE;
Example
DECLARE
c_boss CONSTANT VARCHAR2(4) := ‘BOSS’;
BEGIN
NULL;
END;
Record
TYPE record_type_name IS RECORD(
first_col_name column_datatype,
second_col_name column_datatype, ...);
record_name record_type_name;
Example
DECLARE
TYPE employee IS RECORD(
v_employee_id NUMBER NOT NULL
,v_first_name VARCHAR2(20));
v_employee employee;
BEGIN
NULL;
END;
If statement Example
1. Cursors
2. Explicit Cursors
3. Procedures
4. Functions
5. Parameters-Procedure, Function
6. Exception Handling
7. Triggers
1. Cursors
20
What is cursor ?
In memory work area
Store rows selected from DB
Process one row per time only
Active set is the set of rows the cursor hold.
Supported attributes
%FOUND
%NOTFOUND
%ROWCOUNT
%ISOPEN
III. Advanced
1. Cursors(cont)
21
Implicit cursors
These are created by default when DML statements
like, INSERT, UPDATE, and DELETE statements are
executed. They are also created when a SELECT statement
that returns just one row is executed.
III. Advanced
1. Cursors(cont)
22
Example
DECLARE
v_rows number(5);
BEGIN
UPDATE employee
SET salary = salary + 1000;
IF SQL%NOTFOUND THEN
dbms_output.put_line('None of the salaries where updated');
ELSIF SQL%FOUND THEN
v_rows := SQL%ROWCOUNT;
dbms_output.put_line('Salaries for ' || v_rows || 'employees are
updated');
END IF;
END;
III. Advanced
2. Explicit Cursors
23
III. Advanced
2. Explicit Cursors
24
Example
Declaring a cursor Accessing the cursor
DECLARE BEGIN
CURSOR emp_cur IS OPEN emp_cur;
SELECT * FETCH emp_cur INTO v_record;
FROM emp_tbl process_one_record(v_record);
WHERE salary > 5000; CLOSE emp_cur;
END;
III. Advanced
3. Procedures
25
What is procedures ?
A named PL/SQL block
A procedure has a header and a body
May or may not return values
If stored on DBMS, we call it stored procedures
III. Advanced
3. Procedures(cont)
26
Declaration
CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]
IS
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;
Execution
From the SQL prompt : EXECUTE [or EXEC]
procedure_name;
Within another procedure: procedure_name;
III. Advanced
3. Procedures(cont)
27
Example
CREATE OR REPLACE PROCEDURE employer_details IS
CURSOR emp_cur IS
SELECT first_name, last_name, salary
FROM emp_tbl;
emp_rec emp_cur%ROWTYPE;
BEGIN
FOR emp_rec IN sales_cur
LOOP
dbms_output.put_line(emp_cur.first_name);
END LOOP;
END;
EXECUTE employer_details;
III. Advanced
4. Functions
28
What is functions?
A named PL/SQL block
A function has a header and a body
Must always return a value (different to a procedure)
If stored on DBMS, we call it stored functions
III. Advanced
4. Functions(cont)
29
Declaration
III. Advanced
4. Functions(cont)
30
Execution
Since a function returns a value we can assign it to a variable
variable_name := function_name;
III. Advanced
4. Functions(cont)
31
Example
CREATE OR REPLACE FUNCTION employer_details_func
RETURN VARCHAR(20);
IS
emp_name VARCHAR(20);
BEGIN
SELECT first_name INTO emp_name
FROM emp_tbl
WHERE empID = '100';
RETURN emp_name;
END;
III. Advanced
5. Parameters in Procedure,
32
Functions
3 ways to pass parameters
IN-parameters
OUT-parameters
IN OUT-parameters
III. Advanced
5. Parameters in
33
Procedure, Functions
Example
III. Advanced
6. Exception Handling
34
III. Advanced
6. Exception Handling
36
3 types of exception
Named System Exceptions
Unnamed System Exceptions
User-defined Exceptions
III. Advanced
6. Exception Handling
37
Example
BEGIN
-- Execution section
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line ('A SELECT...INTO did not return any
row.');
END;
III. Advanced
7. Triggers
38
What is a Trigger?
III. Advanced
7. Triggers(cont)
39
III. Advanced
7. Triggers(cont)
40
Example
The price of a product changes constantly. It is important to
maintain the history of the prices of the products.
We can create a trigger to update the 'product_price_history' table
when the price of the product is updated in the 'product' table.
III. Advanced
7. Triggers(cont)
41
Example(cont)
2. Create the price_history_trigger and execute it.
III. Advanced
7. Triggers(cont)
42
Example(cont)
3. Lets update the price of a product.
4. If you ROLLBACK the transaction before committing to the database, the data
inserted to the table is also rolled back.
III. Advanced
7. Triggers(cont)
43
III. Advanced
7. Triggers(cont)
44
This view stores information about header and body of the trigger
SELECT * FROM user_triggers WHERE trigger_name =
'trigger_name';
III. Advanced
IV. Conclusion
45
Now, I hope this slide gave you some ideas about working with PL/SQL.
Please let me know if there’s any mistake or issue in the tutorial. All
comments are welcome.
With our position in CTI Vietnam. This amount of knowledge would not be
enough for us. There’re many more topics we need to invest our time:
performance tuning, data mining, coding convention, best practices, …
So, let’s share our knowledge, TOGETHER.
V. Reference
46
Below is some keywords not mentioned in this slide. If possible, you should
google them.
Questions, please
...