Download presentation
Presentation is loading. Please wait.
Published byPatricia Silva Modified over 5 years ago
1
Chapter 8 Advanced SQL Pearson Education © 2009
2
Chapter 8 - Objectives How to use the SQL programming language
How to use SQL cursors How to create stored procedures How to create triggers How to use triggers to enforce integrity constraints Pearson Education © 2009
3
Chapter 8 – Objectives (continued)
The advantages and disadvantages of triggers How to use recursive queries
4
The SQL Programming Language
Impedance mismatch Mixing different programming paradigms SQL is a declarative language High-level language such as C is a procedural language SQL and 3GLs use different models to represent data
5
The SQL Programming Language (continued)
SQL/PSM (Persistent Stored Modules) PL/SQL (Procedural Language/SQL) Oracle’s procedural extension to SQL Two versions
6
Declarations Variables and constant variables must be declared before they can be referenced Possible to declare a variable as NOT NULL %TYPE and %ROWTYPE
7
Declarations (continued)
8
Examples vRent NUMBER(6, 2) NOT NULL := 600;
vStaffNo Staff.staffNo%TYPE;
9
Assignments Variables can be assigned in three ways:
Using the normal assignment statement (:=) SET SQL SELECT or FETCH statement
10
Examples vX NUMBER; …. vStaffNo := ‘SG14’; vRent := 500;
SELECT COUNT(*) INTO vX FROM PropertyForRent WHERE staffNo = vStaffNo; SET vStaffNo = ‘SG14’;
11
Control Statements Conditional IF statement Conditional CASE statement
Iteration statement (LOOP) Iteration statement (WHILE and REPEAT) Iteration statement (FOR)
12
IF Statement IF ( vPosition = ‘Manager’) THEN vSalary := vSalary * 1.05; ELSIF (…) THEN //optional … ELSE //optional vSalary := vSalary * 1.08; END IF;
13
CASE Statement CASE lowercase(input) WHEN ‘a’ THEN x := 1; WHEN ‘b’ THEN x := 2; y := 3; WHEN ‘default’ THEN x := 3; END CASE;
14
LOOP Statement x := 1; myLoop: LOOP x := x+1; IF (x > 3) THEN EXIT myLoop; END IF; END LOOP myLoop; …
15
WHILE/REPEAT Statement
myLoop: x := 1; WHILE (x < 4) DO x := x+1; END WHILE myLoop; REPEAT UNTIL (x>3) END REPEAT myLoop;
16
FOR Statement SELECT COUNT(*) INTO numberOfStaff FROM …. myLoop: FOR iStaff IN 1..numberOfStaff LOOP …. END LOOP myLoop;
17
Exceptions in PL/SQL Exception Identifier in PL/SQL
Raised during the execution of a block Terminates block’s main body of actions Exception handlers Separate routines that handle raised exceptions User-defined exception Defined in the declarative part of a PL/SQL block
18
Example of Exception Handling in PL/SQL
19
Condition Handling Define a handler by Specifying its type
Exception and completion conditions it can resolve Action it takes to do so Handler is activated When it is the most appropriate handler for the condition that has been raised by the SQL statement
20
Cursors in PL/SQL Cursor
Allows the rows of a query result to be accessed one at a time Must be declared and opened before use Must be closed to deactivate it after it is no longer required Updating rows through a cursor
21
Using Cursors in PL/SQL to Process a Multirow Query
22
Cursor Flags %FOUND: true if the most recent fetch returns a row
%NOTFOUND: true if the most recent fetch returns no row %ISOPEN: true if cursor is open %ROWCOUNT: total number of rows returned so far
23
Cursor Parameter A cursor may be reused with parameter(s):
CURSOR propteryCursor(vStaffNo VARCHAR(4) ) IS SELECT propertyNo, street, city, postcode FROM PropertyForRent WHERE staffNo = vStaffNo ORDER BY propertyNo; Later the cursor can be opened as: OPEN propertyCursor(‘SG14’); … OPEN propertyCursor(‘SA9’);
24
Updating Rows through a Cursor
A row may change after it has been fetched Example: CURSOR propterCursor IS SELECT propertyNo, street, city, postcode FROM PropertyForRent WHERE staffNo = ‘SG14’ ORDER BY propertyNo --Lock the PropertyForRent table immediately FOR UPDATE NOWAIT; Now in the loop: UPDATE PropertyForRent SET staffNo = ‘SG37’ WHERE CURRENT OF propertyCursor; … COMMIT;
25
Subprograms, Stored Procedures, Functions, and Packages
Named PL/SQL blocks that can take parameters and be invoked Types Stored procedures: No return value Functions: Always returns a single value Parameters IN: for input only. Default. OUT: for output value only IN OUT: for input and output
26
Procedure (in PL/SQL) CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters] {IS|AS} Declaration section BEGIN Execution section EXCEPTION Exception section END;
27
Example CREATE PROCEDURE Get_emp_names (Dept_num IN NUMBER) IS Emp_name VARCHAR(10); CURSOR c1 (DepNo NUMBER) IS SELECT Ename FROM Emp_tab WHERE deptNo = DepNo; -- deptNo is an attribute BEGIN OPEN c1(Dept_num); LOOP FETCH c1 INTO Emp_name; EXIT WHEN c1%NOTFOUND; DBMS_OUTPUT.PUT_LINE(Emp_name); END LOOP; CLOSE c1; END;
28
Executing In standalone statement: EXECUTE procedure(parameter list); Called from another PL/SQL block: … procedure(parameter list);
29
Deleting DROP PROCEDURE procedure-name;
30
Function CREATE [OR REPLACE] FUNCTION function_name [ (parameter [,parameter]) ] RETURN return_datatype IS | AS [declaration_section] BEGIN executable_section [EXCEPTION exception_section] END [function_name];
31
Function Example CREATE [OR REPLACE] FUNCTION FindCourse ( name_in IN VARCHAR2 ) RETURN NUMBER IS cnumber NUMBER; CURSOR c1 IS SELECT course_number FROM courses_tbl WHERE course_name = name_in; BEGIN open c1; fetch c1 into cnumber; … close c1; RETURN cnumber; END;
32
Example cont’d SELECT course_name, FindCourse(course_name) AS course_id FROM courses WHERE subject = 'Mathematics';
33
Executing Similar to stored procedures
Pass the required parameters along with function name; If function returns a value, you can store returned value Program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when it last end statement is reached, it returns program control back to the main program.
34
MS SQL Server Stored Procedure Example
To create: CREATE PROCEDURE getAddress VARCHAR(30)) AS BEGIN SELECT * FROM Staff WHERE City END; GO To Execute: EXEC = ‘Houston’;
35
MS SQL Server Function Example
To create: CREATE FUNCTION getSite INT ) RETURNS VARCHAR(50) AS BEGIN VARCHAR(50); < 10 = ‘UHD.edu'; ELSE = ‘Houston.gov'; END; To execute: SELECT dbo.getSite(8);
36
Triggers Trigger Defines an action that the database should take when some event occurs in the application Format of a trigger Types TRIGGER Privilege Advantages and disadvantages of triggers
37
Trigger Format
38
A BEFORE Trigger
39
An After Trigger CREATE TRIGGER StaffAfterInsert AFTER INSERT ON Staff REFERENCEING NEW AS newrow FOR EACH ROW BEGIN INSERT INTO StaffAudit VALUES (:newrow.staffNo, :newrow.fName, :newrow.LName, :newrow.position, :newrow.sex, ….); END;
40
INSTEAD OF Trigger Views are not updateable if there are more than two base tables INSTEAD OF Triggers are used to update views
41
Trigger Privilege Must be the owner of the table
Or have been granted the TRIGGER privilege on the table
42
Trigger Advantages and Disadvantages
Reduce redundancy Simply modifications Increase security Improve integrity Improve processing power … Performance overhead Cascading effects
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.