Download presentation
Presentation is loading. Please wait.
Published byColeen Morrison Modified over 8 years ago
1
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview of PL/SQL IS 320: Introduction to Database Hatoon AlSagri
2
PL/SQL 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.
3
PL/SQL Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL block. There are two types of Blocks in PL/SQL: 1. Anonymous Blocks: Can be written and executed immediately in SQLPLUS. Can be used in triggers. 2. Named Blocks: 1.Procedures. 2.Functions.
4
PL/SQL A PL/SQL Block consists of three sections: 1. The Declaration section (optional). 2. The Execution section (mandatory). 3. The Exception (or Error) Handling section (optional). Declaration Section: The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE. This section is optional and is used to declare any placeholders like variables, constants and cursors, which are used to manipulate data in the execution section.
5
PL/SQL Execution Section: The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends with END. This is a mandatory section It is the section where the program logic is written to perform any task. The programmatic constructs like loops, conditional statement and SQL statements form the part of execution section.
6
PL/SQL Exception Section: The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. This section is optional. Any errors in the program can be handled in this section, so that the PL/SQL Blocks terminates gracefully. If the PL/SQL Block contains exceptions that cannot be handled, the Block terminates abruptly with errors. Every statement in the above three sections must end with ;.
7
PL/SQL DECLARE Variable declaration BEGIN Program Execution EXCEPTION Exception handling END; / NOTE: The backward slash '/' in the above program indicates to execute the above PL/SQL Block.
8
Benefits of PL/SQL 1. Block Structures: PL SQL consists of blocks of code. PL/SQL Blocks can be stored in the database and reused. 2. Procedural Language Capability: PL SQL consists of procedural language constructs such as conditional statements (if else statements) and loops like (FOR loops).
9
Benefits of PL/SQL 3. Better Performance: PL SQL engine processes multiple SQL statements simultaneously as a single block, thereby reducing network traffic. 4. Error Handling: PL/SQL handles errors or exceptions effectively during the execution of a PL/SQL program. Once an exception is caught, specific actions can be taken depending upon the type of the exception or it can be displayed to the user with a message.
10
% TYPE, % ROWTYPE % TYPE provides the data type of a variable or a database column to that variable. % ROWTYPE provides the record type that represents a entire row of a table or view or columns selected in the cursor. The advantages are : 1. Need not know about variable's data type 2. If the database definition of a column in a table changes, the data type of a variable changes ccordingly.
11
% TYPE, % ROWTYPE DECLARE Sname Student.first_name%TYPE; Fav_boat VARCHAR2 (30); My_fav_boat fav_boat%TYPE :=‘pinta’; DECLARE Student_record Student%ROWTYPE;
12
Declaring Variables The General Syntax to declare a variable is: variable_name datatype [NOT NULL := value ]; variable_name is the name of the variable. Data type is a valid PL/SQL data type. NOT NULL is an optional specification on the variable. Value is also an optional specification, where you can initialize a variable. Each variable declaration is a separate statement and must be terminated by a semicolon.
13
Declaring Variables DECLARE salary number (6); “salary” is a variable of datatype number and of length 6. When a variable is specified as NOT NULL, you must initialize the variable when it is declared. For example: The next example declares two variables, one of which is a not null.
14
Declaring Variables DECLARE salary number(4); dept varchar2(10) NOT NULL := “HR Dept”; The value of a variable can change in the execution or exception section of the PL/SQL Block. We can assign values to variables in the two ways given below. 1) We can directly assign values to variables. The General Syntax is: variable_name:= value;
15
Variables 2) We can assign values to variables directly from the database columns by using a SELECT.. INTO statement. The General Syntax is: SELECT column_name INTO variable_name FROM table_name [WHERE condition];
16
Variables Example: The below program will get the salary of an employee with id '1116' and display it on the screen. DECLARE var_salary number(6); var_emp_id number(6) NOT NULL := 1116; BEGIN SELECT salary INTO var_salary FROM employee WHERE emp_id = var_emp_id; dbms_output.put_line(var_salary); dbms_output.put_line('The employee ' || var_emp_id || ' has salary ' || var_salary); END; /
17
Stored Procedures What is a Stored Procedure? A stored procedure or in simple a proc is a named PL/SQL block which performs one or more specific task. A procedure has a header and a body. The header consists of the name of the procedure and the parameters or variables passed to the procedure. The body consists or declaration section, execution section and exception section similar to a general PL/SQL Block. A procedure is similar to an anonymous PL/SQL Block but it is named for repeated usage.
18
Stored Procedures We can pass parameters to procedures in three ways: 1) IN-parameters 2) OUT-parameters 3) IN OUT-parameters A procedure may or may not return any value.
19
Stored Procedures General Syntax to create a procedure is: CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters] IS Declaration section BEGIN Execution section EXCEPTION Exception section END; /
20
Stored Procedures IS - marks the beginning of the body of the procedure and is similar to DECLARE in anonymous PL/SQL Blocks. The code between IS and BEGIN forms the Declaration section. The syntax within the brackets [ ] indicate they are optional. By using CREATE OR REPLACE together the procedure is created if no other procedure with the same name exists or the existing procedure is replaced with the current code.
21
Stored Procedures There are two ways to execute a procedure: 1) From the SQL prompt. EXECUTE [or EXEC] procedure_name; 2) Within another procedure – simply use the procedure name. procedure_name;
22
Stored Procedures CREATE OR REPLACE PROCEDURE employer_details IS CURSOR emp_cur IS SELECT first_name, last_name, salary FROM emp_tbl; emp_rec emp_tbl%rowtype; BEGIN FOR emp_rec in emp_cur LOOP dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name || ' ' ||emp_cur.salary); END LOOP; END; /
23
Function What is a Function in PL/SQL? A function is a named PL/SQL Block which is similar to a procedure. There are some differences between a procedure and a function.
24
Function The General Syntax to create a function is: CREATE [OR REPLACE] FUNCTION function_name [parameters] RETURN return_datatype; IS Declaration_section BEGIN Execution_section Return return_variable; EXCEPTION exception section Return return_variable; END; /
25
Function The header section defines the return type of the function. The execution and exception section both should return a value which is of the datatype defined in the header section.
26
Function For example, let’s create a frunction called ''employer_details_func CREATE OR REPLACE FUNCTION employer_details_func RETURN VARCHAR2(20); IS emp_name VARCHAR2(20); BEGIN SELECT first_name INTO emp_name FROM emp_tbl WHERE empID = '100'; RETURN emp_name; END; /
27
Function To execute the function: declare a varchar2(50); begin a:= employer_details_func; dbms_output.put_line(a); end; /
28
Function How to execute a PL/SQL Function? A function can be executed in the following ways: 1) Since a function returns a value we can assign it to a variable employee_name := employer_details_func; If ‘employee_name’ is of datatype varchar2 we can store the name of the employee by assigning the return type of the function to it. 2) As a part of a SELECT statement SELECT employer_details_func FROM dual; 3) In a PL/SQL Statements like: dbms_output.put_line(employer_details_func); This line displays the value returned by the function.
29
Parameters in Procedure and Functions How to pass parameters to Procedures and Functions in PL/SQL ? In PL/SQL, we can pass parameters to procedures and functions in three ways. 1) IN type parameter: These types of parameters are used to send values to stored procedures. 2) OUT type parameter: These types of parameters are used to get values from stored procedures. This is similar to a return type in functions.
30
Parameters in Procedure and Functions 3) IN OUT parameter: These types of parameters are used to send values and get values from stored procedures. NOTE: If a parameter is not explicitly defined a parameter type, then by default it is an IN type parameter.
31
Parameters in Procedure and Functions 1) IN parameter: This is similar to passing parameters in programming languages. We can pass values to the stored procedure through these parameters or variables. This type of parameter is a read only parameter. We can assign the value of IN type parameter to a variable or use it in a query, but we cannot change its value inside the procedure.
32
Parameters in Procedure and Functions IN parameter: The General syntax to pass a IN parameter is : CREATE [OR REPLACE] PROCEDURE procedure_name ( param_name1 IN datatype, param_name2 IN datatype... ) param_name1, param_name2... are unique parameter names. datatype - defines the datatype of the variable. IN - is optional, by default it is a IN type parameter.
33
Parameters in Procedure and Functions 2) OUT Parameter: The OUT parameters are used to send the OUTPUT from a procedure or a function. This is a write-only parameter i.e, we cannot pass values to OUT parameters while executing the stored procedure, but we can assign values to OUT parameter inside the stored procedure and the calling program can receive this output value.
34
Parameters in Procedure and Functions OUT Parameter: The General syntax to create an OUT parameter is CREATE [OR REPLACE] PROCEDURE proc2 (param_name OUT datatype) The parameter should be explicitly declared as OUT parameter.
35
Parameters in Procedure and Functions 3) IN OUT Parameter: The IN OUT parameter allows us to pass values into a procedure and get output values from the procedure. This parameter is used if the value of the IN parameter can be changed in the calling program. By using IN OUT parameter we can pass values into a parameter and return a value to the calling program using the same parameter. But this is possible only if the value passed to the procedure and output value have a same datatype.
36
Parameters in Procedure and Functions 3) IN OUT Parameter: The General syntax to create an IN OUT parameter is CREATE [OR REPLACE] PROCEDURE proc3 (param_name IN OUT datatype)
37
Parameters in Procedure and Functions Example Using IN and OUT parameter: Let’s create a procedure which gets the name of the employee when the employee id is passed. CREATE OR REPLACE PROCEDURE emp_name (id IN NUMBER, emp_name OUT NUMBER) IS BEGIN SELECT first_name INTO emp_name FROM emp_tbl WHERE empID = id; END; /
38
Parameters in Procedure and Functions Example Using IN and OUT parameter: We can call the procedure ‘emp_name’ in this way from a PL/SQL Block. DECLARE empName varchar2(20) ; empid NUMBER NOT NULL := 601; BEGIN emp_name(empid, empName); dbms_output.putline('The employee ' || empName ); END; /
39
Parameters in Procedure and Functions Example of Using IN OUT parameter in procedures: CREATE OR REPLACE PROCEDURE emp_salary_increase (emp_id IN emptbl.empID%type, salary_inc IN OUT emptbl.salary%type) IS tmp_sal number; BEGIN SELECT salary INTO tmp_sal FROM emp_tbl WHERE empID = emp_id;
40
Parameters in Procedure and Functions Example of Using IN OUT parameter in procedures: IF tmp_sal between 10000 and 20000 THEN salary_inc := tmp_sal * 1.2; ELSIF tmp_sal between 20000 and 30000 THEN salary_inc:= tmp_sal * 1.3; ELSIF tmp_sal > 30000 THEN salary_inc := tmp_sal * 1.4; END IF; END; /
41
Exception Exception Handling In this section we will discuss about the following: 1) What is Exception Handling. 2) Structure of Exception Handling. 3) Types of Exception Handling.
42
Exception 1) What is Exception Handling? PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block known as exception Handling. Using Exception Handling we can test the code and avoid it from exiting suddenly. When an exception occurs a messages which explains its cause is received.
43
Exception PL/SQL Exception message consists of three parts: 1) Type of Exception 2) An Error Code 3) A message By Handling the exceptions we can ensure a PL/SQL block does not exit suddenly.
44
Exception 2) Structure of Exception Handling. The General Syntax for coding the exception section DECLARE Declaration section BEGIN EXCEPTION WHEN ex_name1 THEN -Error handling statements WHEN ex_name2 THEN -Error handling statements WHEN Others THEN -Error handling statements END; /
45
Exception When an exception is raised, Oracle searches for an appropriate exception handler in the exception section. Since, it is not possible to determine all the possible runtime errors during testing of the code, the 'WHEN Others' exception is used to manage the exceptions that are not explicitly handled. Only one exception can be raised in a Block and the control does not return to the Execution Section after the error is handled.
46
Exception If there are nested PL/SQL blocks like this. DELCARE Declaration section BEGIN DECLARE Declaration section BEGIN Execution section EXCEPTION Exception section END; EXCEPTION Exception section END; /
47
Exception In the previous case, if the exception is raised in the inner block it should be handled in the exception block of the inner PL/SQL block. Else the control moves to the Exception block of the next upper PL/SQL Block. If none of the blocks handle the exception the program ends suddenly with an error.
48
Exception 3) Types of Exception. a) Named System Exceptions b) Unnamed System Exceptions c) User-defined Exceptions
49
Exception a) Named System Exceptions System exceptions are automatically raised by Oracle. There are some system exceptions which are raised frequently, so they are pre-defined and given a name in Oracle which are known as Named System Exceptions.
50
Exception Named system exceptions are: 1) Not Declared explicitly. 2) Raised implicitly when a predefined Oracle error occurs. 3) Caught by referencing the standard name within an exception- handling routine.
51
Exception
52
For Example: Suppose a NO_DATA_FOUND exception is raised in a proc, we can write a code to handle the exception as given below. BEGIN Execution section EXCEPTION WHEN NO_DATA_FOUND THEN dbms_output.put_line ('A SELECT...INTO did not return any row.'); END; /
53
Exception b) User-defined Exceptions Apart from system exceptions, we can explicitly define exceptions. Steps to be followed to use user-defined exceptions: They should be explicitly declared in the declaration section. They should be explicitly raised in the Execution Section. They should be handled by referencing the user-defined exception name in the exception section.
54
Exception
55
Example DECLARE huge_quantity EXCEPTION; BEGIN IF condition1 THEN RAISE huge_quantity; END IF; EXCEPTION WHEN huge_quantity THEN Dbms_output.put_line (‘huge_quantity’); END; /
56
Triggers What is a Trigger? A trigger is a PL/SQL block structure which is fired when a DML statements like Insert, Delete, Update is executed on a database table. A trigger is triggered automatically when an associated DML statement is executed.
57
Triggers Syntax of Triggers The Syntax for creating a trigger is: CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF } {INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name [REFERENCING OLD AS o NEW AS n] [FOR EACH ROW] WHEN (condition) BEGIN – -- sql statements END;
58
Triggers CREATE [OR REPLACE ] TRIGGER trigger_name – This clause creates a trigger with the given name or overwrites an existing trigger with the same name. {BEFORE | AFTER | INSTEAD OF } – This clause indicates at what time should the trigger get fired. i.e for example: before or after updating a table. INSTEAD OF is used to create a trigger on a view. before and after cannot be used to create a trigger on a view. {INSERT [OR] | UPDATE [OR] | DELETE} This clause determines the triggering event. More than one triggering events can be used together separated by OR keyword. The trigger gets fired at all the specified triggering event.
59
Triggers [OF col_name] This clause is used with update triggers. This clause is used when you want to trigger an event only when a specific column is updated. CREATE [OR REPLACE ] TRIGGER trigger_name This clause creates a trigger with the given name or overwrites an existing trigger with the same name. [ON table_name] This clause identifies the name of the table or view to which the trigger is associated.
60
Triggers [REFERENCING OLD AS o NEW AS n] This clause is used to reference the old and new values of the data being changed. By default, you reference the values as old.column_name or :new.column_name. The reference names can also be changed from old (or new) to any other user-defined name. You cannot reference old values when inserting a record, or new values when deleting a record, because they do not exist.
61
Triggers [FOR EACH ROW] This clause is used to determine whether a trigger must fire when each row gets affected ( i.e. a Row Level Trigger) or just once when the entire sql statement is executed(i.e.statement level Trigger). WHEN (condition) This clause is valid only for row level triggers. The trigger is fired only for rows that satisfy the condition specified.
62
Triggers Types of PL/SQL Triggers There are two types of triggers based on the which level it is triggered. 1) Row level trigger - An event is triggered for each row updated, inserted or deleted. 2) Statement level trigger - An event is triggered for each sql statement executed.
63
Triggers PL/SQL Trigger Execution Hierarchy The following hierarchy is followed when a trigger is fired.: 1) BEFORE statement trigger fires first. 2) Next BEFORE row level trigger fires, once for each row affected. 3) Then AFTER row level trigger fires once for each affected row. This events will alternates between BEFORE and AFTER row level triggers. 4) Finally the AFTER statement level trigger fires.
64
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Trigger Example
65
Triggers For Example: Let's create a table 'product_check' which we can use to store messages when triggers are fired. CREATE TABLE product_check (Message varchar2(50), Current_Date number(32));
66
Triggers 1) BEFORE UPDATE, Statement Level: This trigger will insert a record into the table 'product_check' before a sql update statement is executed, at the statement level. CREATE or REPLACE TRIGGER Before_Update_Stat_product BEFORE UPDATE ON product Begin INSERT INTO product_check Values('Before update, statement level',sysdate); END; /
67
Triggers 2) BEFORE UPDATE, Row Level: This trigger will insert a record into the table 'product_check' before each row is updated. CREATE or REPLACE TRIGGERBefore_Upddate_Row_product BEFORE UPDATE ON product FOR EACH ROW BEGIN INSERT INTO product_check Values('Before update row level',sysdate); END; /
68
Triggers 3) AFTER UPDATE, Statement Level: This trigger will insert a record into the table 'product_check' after a sql update statement is executed, at the statement level. CREATE or REPLACE TRIGGER After_Update_Stat_product AFTER UPDATE ON product BEGIN INSERT INTO product_check Values('After update, statement level', sysdate); End; /
69
Triggers 4) AFTER UPDATE, Row Level: This trigger will insert a record into the table 'product_check' after each row is updated. CREATE or REPLACE TRIGGER After_Update_Row_product AFTER insert On product FOR EACH ROW BEGIN INSERT INTO product_check Values('After update, Row level',sysdate); END; /
70
Triggers Now lets execute a update statement on table product. UPDATE PRODUCT SET unit_price = 800 WHERE product_id in (100,101); Lets check the data in 'product_check' table to see the order in which the trigger is fired. SELECT * FROM product_check; Output: Mesage Current_Date ------------------------------------------------------------ Before update, statement level 26-Nov-2008 Before update, row level 26-Nov-2008 After update, Row level 26-Nov-2008 Before update, row level 26-Nov-2008 After update, Row level 26-Nov-2008 After update, statement level 26-Nov-2008
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.