Download presentation
Presentation is loading. Please wait.
1
Introduction to PL/SQL
Teaching Tip: If you are using this slideshow in a computer classroom, students can enter commands to the MY_FACULTY and MY_STUDENTS tables as you introduce them. Before using this slideshow, create the tables using the following commands: CREATE TABLE my_faculty (f_id NUMBER(6), f_name VARCHAR2(30)); CREATE TABLE my_students (s_name VARCHAR2 (30), s_dob DATE, s_class CHAR(2), s_age NUMBER(2)); Then have students enter commands as they are introduced.
2
What is PL/SQL? Tight Integration with SQL
PL/SQL is tightly integrated with SQL, the most widely used database manipulation language.
3
What is PL/SQL? PL/SQL lets you use all SQL data manipulation, cursor control, and transaction control statements, and all SQL functions, operators, and pseudocolumns. PL/SQL fully supports SQL data types.
4
What is PL/SQL? High Performance
PL/SQL lets you send a block of statements to the database, significantly reducing traffic between the application and the database.
5
What is PL/SQL? High Productivity
PL/SQL lets you write compact code for manipulating data. Just as a scripting language, we can read, transform, and write data in files, PL/SQL can query, transform, and update data in a database.
6
What is PL/SQL? Portability
You can run PL/SQL applications on any operating system and platform where Oracle Database runs.
7
What is PL/SQL? Scalability
PL/SQL stored subprograms increase scalability by centralizing application processing on the database server.
8
What is PL/SQL? Manageability
PL/SQL stored subprograms increase manageability because you can maintain only one copy of a subprogram, on the database server, rather than one copy on each client system. Any number of applications can use the subprograms, and you can change the subprograms without affecting the applications that invoke them
9
What is PL/SQL? Support for Object-Oriented Programming
Support for Developing Web Applications Support for Developing Server Pages
10
PL/SQL Advantage
11
PL/SQL Variables Variable names must follow the Oracle naming standard
Can use reserved words (BEGIN, NUMBER) and table names for variable names, but is not a good practice Make variable names descriptive Use lower-case letters, and separate words with underscores Example: current_s_id
12
Declaring PL/SQL Variables
PL/SQL is a strongly-typed language All variables must be declared prior to use Syntax for declaring a variable: variable_name data_type_declaration; Example: current_s_id NUMBER(6);
13
PL/SQL Data Types Scalar Composite Data type that store a single value
Data type that do not have any internal component Composite References a data structure Which has internal components
14
PL/SQL Data Types Reference LOB References a specific database item
These data types are also considered pointers. LOB References a large object
15
PL/SQL Data Types Image Source: docs.oracle.com
16
Scalar Data Types Database scalar data types:
VARCHAR2 CHAR DATE LONG NUMBER Non-database scalar data types: Integers: BINARY_INTEGER, INTEGER, INT, SMALLINT Decimal numbers: DEC, DECIMAL, DOUBLE, PRECISION, NUMERIC, REAL BOOLEAN
17
Composite Data Types Reference multiple data elements, such as a record Types: RECORD TABLE VARRAY Tabular structure that can expand or contract as needed
18
Reference Data Types Reference a database item
Assume data type of item %TYPE: assumes data type of field %ROWTYPE: assumes data type of entire row
19
Large Object (LOB) Oracle provides the LOB data type for storing large data up to 4GB. LOB can be used to store text, images, sound file, video file. LOBs are either internal or external depending on their location with respect to the database.
20
Large Object (LOB) Internal LOBs (BLOBs, CLOBs, and NCLOBs)
Internal LOBs are stored inside database tablespaces in a way that optimizes space and enables efficient access.
21
Large Object (LOB) BLOB: A LOB whose value is composed of unstructured binary (raw) data CLOB: A LOB whose value is composed of character data that corresponds to the database character set defined for the Oracle database NCLOB: A LOB whose value is composed of character data that corresponds to the national character set defined for the Oracle database (For supporting National Languages such as French, Italian, Hindi, etc….)
22
PL/SQL Program Structure
DECLARE Variable declarations BEGIN Program statements EXCEPTION Error-handling statements END; Variable Declarations Body Exception Section
23
PL/SQL Program Lines declare a number(4); b number(4); BEGIN a:=4;
DBMS_OUTPUT.PUT_LINE(a+b); END;
24
PL/SQL Program Lines May span multiple text editor lines
Each line ends with a semicolon Text is not case sensitive
25
Comment Statements Block of comments are delimited with /* */
/* <comment that spans more than one line of code> */ Single comment line starts with 2 hyphens -- comment on a single line
26
Arithmetic Operators Example Result
27
Assignment Statements
Assignment operator: := Variable being assigned to a new value is on left side of assignment operator New value is on right side of operator student_name := ‘John Miller’; student_name := current_student;
28
PL/SQL Data Type Conversion Functions
TO_DATE: character string to DATE TO_DATE(‘07/14/01’, ‘MM/DD/YY’); TO_NUMBER: character string to NUMBER TO_NUMBER(‘2’); TO_CHAR: NUMBER or DATE to character string TO_CHAR(2); TO_CHAR(SYSDATE, ‘MM/DD/YYYY HH:MI’);
29
Character String Functions
Concatenating strings: joining 2 or more character strings into a single string Concatenation operator: || s_first_name := ‘BScIT’ s_last_name := ‘MScIT’ s_full_name := s_first_name || ‘ ’ || s_last_name
30
PL/SQL Character String Functions
RTRIM: removes blank trailing spaces cust_address := RTRIM(cust_address); LENGTH: returns string length (number of characters) address_length := LENGTH(cust_address); UPPER, LOWER: changes characters to all upper or lower case s_name := UPPER(s_name); s_name := LOWER(s_name);
31
PL/SQL Character String Functions
INSTR: searches a string and looks for a matching substring and returns its starting position starting_position := INSTR(string_being_searched, search_string>); blank_position := INSTR(‘Sarah Miller’, ‘ ’);
32
PL/SQL Character String Functions
SUBSTR: extracts a specific number of characters from a string, starting at a given point extracted_string := SUBSTR(string_being_searched, starting_point, number_of_characters_to_extract); s_first_name := SUBSTR(‘Sarah Miller’, 1,5);
33
NULL Values in Assignment Statements
Until a value is assigned to a variable, the variable’s value is NULL Performing an arithmetic value on a NULL value always results in a NULL value Advice: Always initialize variable values
34
PL/SQL Selection Structures
IF/THEN IF/END IF: IF condition THEN program statements END IF; IF/ELSE/END IF: ELSE alternate program statements
35
PL/SQL Selection Structures
IF/ELSIF: IF condition1 THEN program statements; ELSIF condition2 THEN alternate program statements; ELSIF condition3 THEN . . . ELSE END IF;
36
PL/SQL Comparison Operators
37
Evaluating NULL Conditions in IF/THEN Structures
If a condition evaluates as NULL, then it is FALSE How can a condition evaluate as NULL? It uses a BOOLEAN variable that has not been initialized It uses any other variable that has not been initialized
38
PL/SQL Loops Loop: repeats one or more program statements multiple times until an exit condition is reached Pretest loop: exit condition is tested before program statements are executed Posttest loop: exit condition is tested after program statements are executed
39
LOOP … EXIT Loop LOOP … EXIT LOOP program statements IF condition THEN
END IF; more program statements END LOOP; Pretest OR Posttest
40
LOOP … EXIT WHEN Loop LOOP program statements EXIT WHEN condition;
END LOOP; Posttest
41
WHILE Loop WHILE … LOOP WHILE condition LOOP program statements
END LOOP; Pretest WHILE … LOOP
42
Numeric FOR Loop FOR counter_variable IN start_value .. end_value LOOP
program statements END LOOP; Preset number of iterations
43
Using SQL Commands in PL/SQL Programs
44
The Client/Server Computing Model
A Client/Server system has three distinct components, each focusing on a specific job. (1) Database server (2) Client application (3) Network
45
The Client/Server Computing Model
Database servers tasks: (1) Managing a single database of information among many concurrent users. (2) Controlling database access and other security requirements. (Cntd….)
46
The Client/Server Computing Model
Database servers tasks: (3) Protecting database information with backup and recovery features. (4) Centrally enforcing global data integrity rules across all client applications.
47
The Client/Server Computing Model
Client Application tasks: Presenting interface a user can interact with to accomplish work. Managing presentation logic such as pop-up list on a data-entry form or bar graphs in a graphical data presentation tool. Performing application logic, such as calculating field in a data entry form.
48
The Client/Server Computing Model
Client Application tasks: Validating data entry. Requesting and receiving information from a database server.
49
The Client/Server Computing Model
Network: The Network and Communication software are the vehicles that transmit data between the client and the server in a system. Both the clients and the server run communication software that allows them to talk across the network.
50
Transaction Control A transaction is a series of SQL statements that either succeeds or fails as a unit. Transactions are a standard part of relational databases and prevent inconsistent data.
51
Transaction Control UPDATE accounts
SET balance=balance–transaction_amt WHERE account_no = from_account SET balance=balance+transaction_amt WHERE account_no=to_account
52
COMMIT vs. ROLLBACK When a COMMIT statement is issued to the database, the transaction is ended, and: (1)All work done by the transaction is made permanent. (2)the other sessions can see the changes made by this transaction. (3)Any locks acquired by the transaction are released. The syntex: COMMIT [WORK];
53
COMMIT vs. ROLLBACK When a ROLLBACK statements is issued to the database, the transaction is ended, and: (1) All work done by the transaction is undone, as if it had not been issued. (2) Any locks acquired by the transaction are released.
54
SAVEPOINT With the SAVEPOINT command it is possible to undo only the part of the transaction. SAVEPOINT is often used before a complicated section of a transaction. If this part of the transaction fails, it can be rolled back, allowing earlier part to continue. SAVEPOINT name;
55
SAVEPOINT Once a SAVEPOINT is defined, the programs can ROLLBACK to the SAVEPOINT via the following command, ROLLBACK [WORK] TO SAVEPOINT name;
56
SAVEPOINT When a ROLLBACK TO SAVEPOINT is
(1) Any work done since the SAVEPOINT is undone. However, The SAVEPOINT remains active. It can be rolled back again. (2) Any locks and resources acquired by the SQL statements since the SAVEPOINT will be released. (3) The transaction is not finished.
57
SAVEPOINT EXAMPLE 1 BEGIN INSERT INTO emp VALUES (1,’A’,1);
SAVEPOINT A; INSERT INTO emp VALUES (1,’B’,1); SAVEPOINT B; INSERT INTO emp VALUES (1,’C’,1); SAVEPOINT C; ROLLBACK TO A; COMMIT; END;
58
SAVEPOINT EXAMPLE 2 BEGIN INSERT INTO emp VALUES (1,’A’,1);
SAVEPOINT A; INSERT INTO emp VALUES (1,’B’,1); SAVEPOINT B; INSERT INTO emp VALUES (1,’C’,1); SAVEPOINT C; ROLLBACK TO B; COMMIT; END;
59
SAVEPOINT EXAMPLE 3 BEGIN INSERT INTO emp VALUES (1,’A’,1);
SAVEPOINT A; INSERT INTO emp VALUES (1,’B’,1); SAVEPOINT B; INSERT INTO emp VALUES (1,’C’,1); SAVEPOINT C; ROLLBACK TO C; COMMIT;s END;
60
Sequences The Oracle sequence generator generates sequences of unique integers that application can use as primary key values for insert intensive applications. In Oracle, you can create an autonumber field by using sequences. A sequence is an object in Oracle that is used to generate a number sequence. This can be useful when you need to create a unique number to act as a primary key.
61
Creating Sequence CREATE SEQUENCE StudentSeq START WITH 1
INCREMENT BY 1 NOMINVALUE NOMAXVALUE NOCYCLE NOCACHE
62
Creating Sequence CREATE SEQUENCE supplier_seq MINVALUE 1
MAXVALUE START WITH 1 INCREMENT BY 1 CACHE 20;
63
Creating Sequence If you omit the MAXVALUE option, your sequence will automatically default to: MAXVALUE So you can simplify your CREATE SEQUENCE command as follows: CREATE SEQUENCE supplier_seq MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 20;
64
Creating Sequence The CACHE parameter lets you pre-generate and cache a number of integers all at one time to reduce the disk input-output when application use the sequence.
65
Creating Sequence Question: While creating a sequence, what does cache and nocache options mean? For example, you could create a sequence with a cache of 20 as follows: CREATE SEQUENCE supplier_seq MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 20;
66
Creating Sequence Or you could create the same sequence with the nocache option: CREATE SEQUENCE supplier_seq MINVALUE 1 START WITH 1 INCREMENT BY 1 NOCACHE;
67
Creating Sequence With respect to a sequence, the cache option specifies how many sequence values will be stored in memory for faster access. Nocache means that none of the sequence values are stored in memory. This option may sacrifice some performance, however, you should not encounter a gap in the assigned sequence values.
68
Creating Sequence The downside of creating a sequence with a cache is that if a system failure occurs, all cached sequence values that have not be used, will be "lost". This results in a "gap" in the assigned sequence values. When the system comes back up, Oracle will cache new numbers from where it left off in the sequence, ignoring the so called "lost" sequence values. Note: To recover the lost sequence values, you can always execute an ALTER SEQUENCE command to reset the counter to the correct value.
69
Using Sequence in Application
To reference a Sequence and generate a new sequence number, reference the sequence with pseudo-column NEXTVL.
70
Using Sequence in Application
INSERT INTO Student VALUES (StudentSeq.NEXTVAL, ‘abc’, ‘xyz’); INSERT INTO Result VALUES (StudentSeq.CURRVAL,50,30,20);
71
Altering Sequences ALTER SEQUENCE StudentSeq CACHE 50
72
Triggers (1)Maintaining complex integrity constraints not possible through declarative constraints enabled at table creation. (2) Automatically signalling other programs that action needs to take place, when changes are made to a table. (3) Auditing information in a table, by recording the changes made and who made them.
73
SYNTAX CREATE [OR REPLACE] TRIGGER trigger_name
{BEFORE|AFTER} triggering_event ON table_reference [FOR EACH ROW [WHEN trigger_condition]] trigger_body;
74
Triggers SYNTAX table_reference is the table for which the trigger is defined. Trigger_body is the main code for the trigger. The trigger_condition in the WHEN clause, is evaluated first. The body of the trigger is executed only when this condition evaluates to TRUE.
75
Category Value Description Events INSERT, DELETE, UPDATE Defines which kind of DML statement causes the trigger to fire. Timing BEFORE or AFTER Defines whether the trigger fires before the statement is executed or after the statement is executed. Level ROW or STATEMENT If the trigger is row-level trigger, it fires once for each row affected by the triggering statement. If the trigger is a statement level trigger, it fires once, for statement. A row-level trigger is identified b the FOR EACH ROW clause in the triggering definition.
76
Image Source: Oracle
77
Restriction on Triggers
A trigger may not issue any transaction control statements- COMMIT, ROLLBACK, and SAVEPOINT. Any procedure or functions that are called by the trigger cannot issue any transaction control statement. The trigger body cannot declare any LONG or LONG ROW variable.
78
Using :old and :new in Row-Level Triggers
A Row-level Trigger fires its body once for every row that the triggering statement touches. Inside the trigger you can access the row currently being processed. This is accomplished by two pseudo-records -:old and :new.
79
Using :old and :new in Row-Level Triggers
Within a trigger body of a row trigger, the PL/SQL code and SQL statements have access to the old and new column values of the current row affected by the triggering statement. Two correlation names exist for every column of the table being modified: one for the old column value, and one for the new column value.
80
Using :old and :new in Row-Level Triggers
Depending on the type of triggering statement, certain correlation names might not have any meaning. A trigger fired by an INSERT statement has meaningful access to new column values only. Because the row is being created by the INSERT, the old values are null.
81
Using :old and :new in Row-Level Triggers
A trigger fired by an UPDATE statement has access to both old and new column values for both BEFORE and AFTER row triggers. A trigger fired by a DELETE statement has meaningful access to :old column values only. Because the row no longer exists after the row is deleted, the :new values are NULL.
82
Using :old and :new in Row-Level Triggers
A new column value can be assigned in a BEFORE row trigger, but not in an AFTER row trigger (because the triggering statement takes effect before an AFTER row trigger is fired). Correlation names can also be used in the Boolean expression of a WHEN clause. A colon must precede the old and new qualifiers when they are used in a trigger's body, but a colon is not allowed when using the qualifiers in the WHEN clause
83
Using :old and :new in Row-Level Triggers
84
Trigger EXAMPLE CREATE TRIGGER student_delete BEFORE DELETE ON student
FOR EACH ROW BEGIN INSERT INTO student_history VALUES (:OLD.SNO, :OLD.FNAME, :OLD.LNAME, :OLD.SEMNO); END;
85
Trigger EXAMPLE CREATE OR REPLACE TRIGGER student_delete
BEFORE DELETE ON student FOR EACH ROW WHEN (OLD.SEMNO=1) BEGIN INSERT INTO student_history VALUES (:OLD.SNO, :OLD.FNAME, :OLD.LNAME, :OLD.SEMNO); END;
86
TRIGGER EXAMPLE STEP1 CREATE TABLE ITEMS ( PID NUMBER(6),
PNAME VARCHAR2(200), CURRENTQTY NUMBER(6), MINQTY NUMBER(6) )
87
TRIGGER EXAMPLE STEP2 CREATE TABLE ITEMS_REORDER_INFO ( PID NUMBER(6),
TDATE DATE )
88
TRIGGER EXAMPLE STEP3 CREATE OR REPLACE TRIGGER ITEMS_REORDER_TRIGGER
AFTER UPDATE ON ITEMS FOR EACH ROW BEGIN IF :NEW.CURRENTQTY < :NEW.MINQTY THEN INSERT INTO ITEMS_REORDER_INFO VALUES (:NEW.PID, SYSDATE); END IF; END;
89
TRIGGER EXAMPLE STEP4 INSERT INTO ITEMS VALUES (1, 'PEN', 10, 5);
INSERT INTO ITEMS VALUES (2, 'BALL', 10, 5); INSERT INTO ITEMS VALUES (3, 'PENCIL', 10, 5);
90
TRIGGER EXAMPLE STEP5 SELECT * FROM ITEMS;
SELECT * FROM ITEMS_REORDER_INFO;
91
TRIGGER EXAMPLE STEP6 UPDATE ITEMS SET CURRENTQTY = 2 WHERE PID = 1;
92
TRIGGER EXAMPLE STEP7 SELECT * FROM ITEMS_REORDER_INFO;
97
CASCADING TRIGGERS Excessive use of Triggers should be avoided. Image Source: Oracle
98
Cursors Pointer to a server memory location
Contains information about a SQL command in a PL/SQL program Called the command’s context area
99
Number of rows processed
Cursors Database Server Memory Cursor Number of rows processed Parsed command statement context area active set
100
Types of Cursors Implicit Explicit
101
Explicit Cursors Must be declared in program DECLARE section
Can be used to assign the output of a SELECT command to one or more PL/SQL variables Can be used if query returns multiple records or no records
102
Using an Explicit Cursor
Declare the cursor Open the cursor Fetch the cursor result into PL/SQL program variables Close the cursor
103
Declaring an Explicit Cursor
DECLARE CURSOR cursor_name IS SELECT_statement; CURSOR SEM3TO4CURSOR IS SELECT * FROM SEM3;
104
Opening an Explicit Cursor
OPEN cursor_name; OPEN SEM3TO4CURSOR;
105
Fetching Explicit Cursor Records
FETCH cursor_name INTO variable_name(s); FETCH SEM3TO4CURSOR INTO V_ROLLNO, V_FNAME, V_LNAME;
106
Closing an Explicit Cursor
CLOSE cursor_name; CLOSE SEM3TO4CURSOR;
107
CURSOR SEM3TO4CURSOR IS SELECT * FROM sem3;
DECLARE V_ROLLNO SEM3.ROLLNO%TYPE; V_FNAME SEM3.FNAME%TYPE; V_LNAME SEM3.LNAME%TYPE; CURSOR SEM3TO4CURSOR IS SELECT * FROM sem3; BEGIN OPEN SEM3TO4CURSOR; LOOP FETCH SEM3TO4CURSOR INTO V_ROLLNO, V_FNAME, V_LNAME; EXIT WHEN SEM3TO4CURSOR%NOTFOUND; INSERT INTO SEM4 VALUES (V_ROLLNO, V_FNAME,V_LNAME); END LOOP; CLOSE SEM3TO4CURSOR; COMMIT; END;
108
Explicit Cursor Attributes
109
Example: %rowcount attribute
Declare cursor C_student is SELECT * FROM STUDENTS; TEMP_STUDENT STUDENT%ROWTYPE; BEGIN OPEN C_student; dbms_output.put_line(TO_CHAR(C_student%ROWCOUNT); FETCH C_student INTO TEMP_STUDENT; CLOSE C_student; END;
110
Example: %rowcount attribute, with error
Declare cursor C_student is SELECT * FROM STUDENTS; TEMP_STUDENT STUDENT%ROWTYPE; BEGIN OPEN C_student; dbms_output.put_line(TO_CHAR(C_student%ROWCOUNT); FETCH C_student INTO TEMP_STUDENT; CLOSE C_student; dbms_output.put_line(TO_CHAR(C_student%ROWCOUNT); ? END;
111
Implicit Cursors Created automatically every time you use an INSERT, UPDATE, DELETE, or SELECT command Doesn’t need to be declared Can be used to assign the output of a SELECT command to one or more PL/SQL variables Can only be used if query returns one and only one record
112
Implicit Cursor Syntax
SELECT field1, field2, … INTO variable1, variable2, … FROM tablename WHERE search_condition_that_will_ return_a_single_record;
113
Implicit Cursor Example:
BEGIN UPDATE ROOMS SET NUMBER_SEATS = 100 WHERE ROOM_ID = 9999; --IF PREVIOUS UPDATE STATEMENT DID NOT MATCH ANY ROW --INSERT A NEW ROW INTO ROOM TABLE IF SQL%NOTFOUND THEN INSERT INTO ROOMS (ROOM_ID, NUMBER_SEATS) VALUES (9999,100); END IF; END;
114
Implicit Cursor Example:
BEGIN UPDATE ROOMS SET NUMBER_SEATS = 100 WHERE ROOM_ID = 9999; --IF PREVIOUS UPDATE STATEMENT DID NOT MATCH ANY ROW --INSERT A NEW ROW INTO ROOM TABLE IF SQL%ROWCOUNT=0 THEN INSERT INTO ROOMS (ROOM_ID, NUMBER_SEATS) VALUES (9999,100); END IF; END;
115
COPY STUDENTS’ DATA WHO ARE PLACED IN 10TH SEM
STUDENT_PLACED SID FNAME LNAME SEMESTER CURRENT_DATE CONTAINS ALL STUDENTS’ DATA STUDENT_MASTER_TABLE SID FNAME LNAME SEMESTER BIRTHDATE CATEGORY PLACED COPY STUDENTS’ DATA WHO ARE NOT PLACED IN 10TH SEM STUDENT_NOT_PLACED SID FNAME LNAME SEMESTER CURRENT_DATE
116
Procedures Advantages
(1) Compiled SQL statements (2) Reduced network traffic (3) Improved security (4) Improved data integrity (5) Thinner clients (6) Modular Programming
117
Procedures CREATE [OR REPLACE] PROCEDURE procedure_name
[(Argument1 [IN|OUT|IN OUT] DATATYPE, Argument2 [IN|OUT|IN OUT] DATATYPE, ………… )] AS {PL/SQL BLOCK};
120
Procedures The IN is used for arguments for which values must be specified when calling the procedure. The OUT signifies that the procedure passes a value back to the caller through this argument. The IN OUT signifies that the argument is both an IN and an OUT.
125
Procedures CREATE PROCEDURE new_emp(ename IN VARCHAR2, eage IN NUMBER)
AS BEGIN INSERT INTO emp values (ename, eage); END; begin New_emp(‘abc’,40); End;
126
Procedures CREATE PROCEDURE fire_emp(eno IN VARCHAR2) AS
DELETE FROM emp WHERE ENO = eno; END; Fire_emp(5); Fire_emp(7);
127
Procedure Example PROCEDURE Get_emp_rec (
Emp_number IN Emp_tab.Empno%TYPE, Emp_ret OUT Emp_tab%ROWTYPE) IS BEGIN SELECT Empno, Ename, Job, Mgr, Hiredate, Sal, Comm, Deptno INTO Emp_ret FROM Emp_tab WHERE Empno = Emp_number; END;
128
Procedure Example DECLARE
Emp_row Emp_tab%ROWTYPE; declare a record matching a -- row in the Emp_tab table BEGIN Get_emp_rec(7499, Emp_row); -- call for Emp_tab# 7499 DBMS_OUTPUT.PUT(Emp_row.Ename || ' ' || Emp_row.Empno); DBMS_OUTPUT.PUT(' ' || Emp_row.Job || ' ' || Emp_row.Mgr); DBMS_OUTPUT.PUT(' ' || Emp_row.Hiredate || ' ' || Emp_row.Sal); DBMS_OUTPUT.PUT(' ' || Emp_row.Comm || ' '|| Emp_row.Deptno); DBMS_OUTPUT.NEW_LINE; END;
129
Write Procedure that will display Student ID (SID) that has scored highest percentage for a particular Exam Month Year and Semester STUDENT_MARKS SID SEMESTER SUB1 SUB2 SUB3 PERCENTAGE GRADE EXAMMONTHYEAR 1 50 B JUNE14 2 55 3 45 C 4 60 A 5 70
130
Write Procedure that will display count of students that has secured ‘A’ GRADE for a particular Exam Month Year and Semester STUDENT_MARKS SID SEMESTER SUB1 SUB2 SUB3 PERCENTAGE GRADE EXAMMONTHYEAR 1 50 B JUNE14 2 55 3 45 C 4 60 A 5 70
131
Write Procedure that will display count of students for a particular Exam Month Year, Grade and Semester STUDENT_MARKS SID SEMESTER SUB1 SUB2 SUB3 PERCENTAGE GRADE EXAMMONTHYEAR 1 50 B JUNE14 2 55 3 45 C 4 60 A 5 70
132
Function CREATE [OR REPLACE] FUNCTION function_name
[(Argument1 [IN|OUT|IN OUT] DATATYPE, Argument2 [IN|OUT|IN OUT] DATATYPE, )] RETURN DATATYPE AS {PL/SQL BLOCK};
133
PL/SQL Exception Handling
All error handling statements are placed in the EXCEPTION program block Exception handler: program command that provides information about an error, and suggest correction actions
134
Predefined Exceptions
137
EXAMPLE 1 DECLARE testnumber number(6); BEGIN TESTNUMBER := 6;
DBMS_OUTPUT.PUT_LINE(TESTNUMBER/0); END;
138
EXAMPLE 2 DECLARE TESTNUMBER NUMBER(6); TESTNUMBER1 NUMBER(6); BEGIN
TESTNUMBER1 := TESTNUMBER/0; EXCEPTION WHEN ZERO_DIVIDE THEN DBMS_OUTPUT.PUT_LINE('DIVIDE BY ZERO EXCEPTION EXECUTED'); END;
139
EXAMPLE 3 DECLARE TEMPROW STUDENT%ROWTYPE; BEGIN
SELECT * INTO TEMPROW FROM STUDENT WHERE SNO=2; EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('NO RECORD FOUND FROM SELECT QUERY'); END;
140
EXAMPLE 4 DECLARE TEMPNO NUMBER(6); TEMPNO1 NUMBER(6); BEGIN
TEMPNO1 := TEMPNO / 0; EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('NO RECORD FOUND FROM SELECT QUERY'); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('CATCH ALL STATEMENT EXECUTED'); END;
141
Exception Handler Syntax For Predefined Exceptions
WHEN exception1_name THEN exception handling statements; WHEN exception2_name THEN … WHEN OTHERS THEN
142
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ] IS [declaration_section] BEGIN executable_section EXCEPTION WHEN exception_name1 THEN [statements] WHEN exception_name2 THEN WHEN exception_name_n THEN WHEN OTHERS THEN END [procedure_name];
143
CREATE OR REPLACE PROCEDURE add_new_supplier
(supplier_id_in IN NUMBER, supplier_name_in IN VARCHAR2) IS BEGIN INSERT INTO suppliers (supplier_id, supplier_name ) VALUES ( supplier_id_in, supplier_name_in ); EXCEPTION WHEN DUP_VAL_ON_INDEX THEN raise_application_error (-20001,'You have tried to insert a duplicate supplier_id.'); WHEN OTHERS THEN raise_application_error (-20002,'An error has occurred inserting a supplier.'); END;
144
User-Defined Exceptions
Errors that will not cause a run-time error, but will violate business rules Programmer creates a custom error message
145
User-Defined Exceptions
Step 1 declare exception (declaration block) Step 2 raise exception (execution block) Step 3 handle exception (exception block)
146
DECLARE emp_sal EMP.SAL%TYPE; emp_no EMP.EMPNO%TYPE; too_high_sal exception; BEGIN select EMPNO, SAL into emp_no, emp_sal from EMP where ENAME = 'KING'; if emp_sal * 1.05 > 4000 then RAISE too_high_sal; end if; EXCEPTION when NO_DATA_FOUND then rollback; when too_high_sal then insert into HighSalaryEmpTable values SrId, emp_no); commit; END;
147
CREATE OR REPLACE PROCEDURE add_new_order
(order_id_in IN NUMBER, sales_in IN NUMBER) IS no_sales EXCEPTION; BEGIN IF sales_in = 0 THEN RAISE no_sales; ELSE INSERT INTO orders (order_id, total_sales ) VALUES ( order_id_in, sales_in ); END IF; EXCEPTION WHEN no_sales THEN raise_application_error (-20001,'You must have sales in order to submit the order.'); WHEN OTHERS THEN raise_application_error (-20002,'An error has occurred inserting an order.'); END;
149
If a PL/SQL program is executed from the SQL
If a PL/SQL program is executed from the SQL *Plus shell, exception handling routines may contain statements that display error or warning messages on the screen. For this, the procedure raise_application_error can be used. This procedure has two parameters <error_number> and <message text>.
150
raise_application_error
Example: if emp_sal * 1.05 > 4000 then raise_application_error (-20010, 'Salary for employee Id ' || to_char(Emp_no) || ' is too high'); <error_number> is a negative integer defined by the user and must range between and
151
Nested PL/SQL Program Blocks
An inner program block can be nested within an outer program block DECLARE variable declarations BEGIN program statements EXCEPTION error handling statements END; Outer block DECLARE variable declarations BEGIN program statements EXCEPTION error handling statements END; Inner block
152
Exception Handling in Nest Program Blocks
If an exception is raised and handled in an inner block, program execution resumes in the outer block
153
Exception Handling in Nested Program Blocks
DECLARE variable declarations BEGIN program statements additional program statements EXCEPTION error handling statements END; DECLARE exception_A BEGIN RAISE exception_A EXCEPTION exception_A error handler END; Exception is raised and handled in inner block Program execution resumes here
154
Exception Handling in Nested Program Blocks
Exceptions raised in inner blocks can be handled by exception handlers in outer blocks
155
NOCOPY IN PROCEDURE Oracle8i includes a compiler hint known as NOCOPY.
The syntax for declaring a parameter with this hint is: parameter_name [mode] NOCOPY datatype IN OUT IN OUT
156
NOCOPY IN PROCEDURE 1) where parameter_name is the name of the parameter, 2) mode is the parameter mode (IN, OUT, or IN OUT), 3) datatype is the parameter datatype. 4) If NOCOPY is present, the PL/SQL compiler will try to pass the parameter by reference, rather than by value. 5) NOCOPY is a compiler hint, rather than a directive, so it will not always be taken
157
NOCOPY IN PROCEDURE When a parameter is passed by reference, any modifications to the formal parameter also modify the actual parameter, because both point to the same location. This means that if a procedure exits with an unhandled exception after the formal parameter has been changed, the original value of the actual parameter will be lost.
158
EXAMPLE:NOCOPY IN PROCEDURE
CREATE OR REPLACE PROCEDURE RaiseErrorNoCopy ( p_Raise IN BOOLEAN, p_ParameterA OUT NOCOPY NUMBER) AS BEGIN p_ParameterA := 7; IF p_Raise THEN RAISE DUP_VAL_ON_INDEX; ELSE RETURN; END IF; END RaiseErrorNoCopy;
159
DECALRE v_Num NUMBER := 1; BEGIN DBMS_OUTPUT.PUT_LINE('Value before first call: ' || v_Num); RaiseErrorNoCopy(FALSE, v_Num); DBMS_OUTPUT.PUT_LINE('Value after successful call: ' || v_Num); DBMS_OUTPUT.PUT_LINE(''); v_Num := 2; DBMS_OUTPUT.PUT_LINE('Value before second call: ' || v_Num); RaiseErrorNoCopy(TRUE, v_Num); EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('Value after unsuccessful call: ' || v_Num); END;
160
OUTPUT AND EXPLANATION
Value before first call: 1 Value after successful call: 7 Value before second call: 2 Value after unsuccessful call: 7 The actual parameter has been modified both times, even when the exception was raised. Example Source: Oracle database 10g PL/SQL, ORACLE PRESS Author Names: Scott et. al.
161
Packages A package is a schema object that allow related objects to be stored together. A package has two distinct parts: Package specification Package body Package body and Package specification are stored separately in the data dictionary.
162
Packages It is essential for a good programming style that logically related blocks, procedures, and functions are combined into modules, and each module provides an interface which allow users and designers to utilize the implemented functionality. PL/SQL supports the concept of modularization by which modules and other constructs can be organized into packages.
163
Packages A package consists of a package specification and a package body. The package specification defines the interface that is visible for application programmers, and the package body implements the package specification. (Similar to header and source files in the programming language C).
164
Package Diagram
174
Package Example
175
Package Example
176
Package Example
180
Packages Example CREATE PACKAGE manage_employee AS
FUNCTION hire_emp (name varchar2, hiredate date); PROCEDURE fire_emp (emp_id NUMBER); END manage_employee;
181
Packages Example CREATE PACKAGE BODY manage_employee AS
FUNCTION hire_emp (name varchar2, hiredate date) IS new_empno NUMBER(10); BEGIN SELECT emp_sequence.NEXTVAL INTO new_empno FROM dual; INSERT INTO emp VALUES(new_empno, name, hiredate); END hire_emp;
182
Packages Example PROCEDURE fire_emp(emp_id NUMBER) IS BEGIN
DELETE FROM emp WHERE empno = emp_id; IF SQL%NOTFOUND THEN raise_application_error (-20011, 'Employee with Id ' || to_char(emp_id) || ' does not exist.'); END IF; END fire_emp; END manage_employee;
183
Packages Example A procedure or function implemented in a package can be called from other procedures and functions using the statement <package name>.<procedure name>[(<list of parameters>)].
184
Packages Oracle offers several predefined packages and procedures that can be used by database users and application developers. A set of very useful procedures is implemented in the package DBMS_OUTPUT.
197
Packages
198
Index An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each value that appears in the indexed columns. By default, Oracle creates B-tree indexes.
199
Create an Index CREATE [UNIQUE] INDEX index_name
ON table_name (column1, column2, . column_n) [ COMPUTE STATISTICS ]; UNIQUE indicates that the combination of values in the indexed columns must be unique.
200
Create an Index COMPUTE STATISTICS tells Oracle to collect statistics during the creation of the index. The statistics are then used by the optimizer to choose a "plan of execution" when SQL statements are executed.
201
Examples CREATE INDEX supplier_idx ON supplier (supplier_name);
ON supplier (supplier_name, city); ON supplier (supplier_name, city) COMPUTE STATISTICS;
202
Create a Function-Based Index
In Oracle, you are not restricted to creating indexes on only columns. You can create function-based indexes. CREATE [UNIQUE] INDEX index_name ON table_name (function1, function2, . function_n) [ COMPUTE STATISTICS ];
203
Create a Function-Based Index
CREATE INDEX supplier_idx ON supplier (UPPER(supplier_name)); In this example, we've created an index based on the uppercase evaluation of the supplier_name field.
204
Create a Function-Based Index
However, to be sure that the Oracle optimizer uses this index when executing your SQL statements, be sure that UPPER(supplier_name) does not evaluate to a NULL value. To ensure this, add UPPER(supplier_name) IS NOT NULL to your WHERE clause as follows:
205
Create a Function-Based Index
SELECT supplier_id, supplier_name, UPPER(supplier_name) FROM supplier WHERE UPPER(supplier_name) IS NOT NULL ORDER BY UPPER(supplier_name);
206
User, Roles, and Privileges
Every Oracle user has a name and password, and owns any table, views, and other resources that he or she created. An Oracle Role is a set of Privileges (or the type of access that each user needs, depending upon his or her status and responsibilities.).
207
User, Roles, and Privileges
You can grant or revoke specific privileges to roles and then assign roles to the appropriate users. A user can also grant privileges directly to other users.
208
User, Roles, and Privileges
There are two different types of privileges – object and system. An Object privilege allows an operation on a particular object such as table. A system privilege allows operation on an entire class of object.
209
User, Roles, and Privileges
GRANT GRANT privilege ON object TO grantee [WITH GRANT OPTION];
210
GRANT GRANT privilege ON object TO grantee [WITH GRANT OPTION];
Where privilege is the desired privilege, object is the object to which access is granted, and grantee is the user who will receive the privilege.
211
GRANT GRANT SELECT ON emp TO rollno1;
If the WITH GRANT OPTION is specified, then rollno1 can in turn grant the privilege to another user. More then one privilege can be specified in one GRANT statement. For example, GRANT UPDATE, DELETE ON emp TO rollno1;
212
GRANT For system privileges, the syntax is
GRANT privilege TO grantee [WITH ADMIN OPTION] GRANT CREATE TABLE TO rollno1; Note: Since grant is a DDL statement, it takes effect immediately and issues an implicit COMMIT after execution.
213
REVOKE If WITH ADMIN OPTION is specified then grantee can grant the privileges to other user as well. REVOKE privileges ON object FROM grantee [CASCADE CONSTRAINT]; REVOKE SELECT ON emp FROM rollno1;
214
REVOKE If the CASCADE CONSTRAINTS clause is included and the REFERENCES privilege is being revoked, all referential integrity constraints created by grantee with this privilege are dropped as well.
215
Object Privilege Objects Description ALTER Tables, sequences Allows grantee to issue an ALTER statement on the object. DELETE Tables, views Allows grantee to issue a DELETE statement against the object. EXECUTE Procedure, functions, packages Allows grantee to execute the stored PL/SQL object. INDEX Tables Allows grantee to create an index on the table. INSERT Allows grantee to use INSERT statement SELECT Tables, views sequences Allow grantee to issue to SELECT statement. UPDATE Allow grantee to issue an UPDATE
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.