Chapter 8 Advanced SQL Pearson Education © 2009
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
Chapter 8 – Objectives (continued) The advantages and disadvantages of triggers How to use recursive queries
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
The SQL Programming Language (continued) SQL/PSM (Persistent Stored Modules) PL/SQL (Procedural Language/SQL) Oracle’s procedural extension to SQL Two versions
Declarations Variables and constant variables must be declared before they can be referenced Possible to declare a variable as NOT NULL %TYPE and %ROWTYPE
Declarations (continued)
Examples vRent NUMBER(6, 2) NOT NULL := 600; vStaffNo Staff.staffNo%TYPE;
Assignments Variables can be assigned in three ways: Using the normal assignment statement (:=) SET SQL SELECT or FETCH statement
Examples vX NUMBER; …. vStaffNo := ‘SG14’; vRent := 500; SELECT COUNT(*) INTO vX FROM PropertyForRent WHERE staffNo = vStaffNo; SET vStaffNo = ‘SG14’;
Control Statements Conditional IF statement Conditional CASE statement Iteration statement (LOOP) Iteration statement (WHILE and REPEAT) Iteration statement (FOR)
IF Statement IF ( vPosition = ‘Manager’) THEN vSalary := vSalary * 1.05; ELSIF (…) THEN //optional … ELSE //optional vSalary := vSalary * 1.08; END IF;
CASE Statement CASE lowercase(input) WHEN ‘a’ THEN x := 1; WHEN ‘b’ THEN x := 2; y := 3; WHEN ‘default’ THEN x := 3; END CASE;
LOOP Statement x := 1; myLoop: LOOP x := x+1; IF (x > 3) THEN EXIT myLoop; END IF; END LOOP myLoop; …
WHILE/REPEAT Statement myLoop: x := 1; WHILE (x < 4) DO x := x+1; END WHILE myLoop; REPEAT UNTIL (x>3) END REPEAT myLoop;
FOR Statement SELECT COUNT(*) INTO numberOfStaff FROM …. myLoop: FOR iStaff IN 1..numberOfStaff LOOP …. END LOOP myLoop;
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
Example of Exception Handling in PL/SQL
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
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
Using Cursors in PL/SQL to Process a Multirow Query
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
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’);
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;
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
Procedure (in PL/SQL) CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters] {IS|AS} Declaration section BEGIN Execution section EXCEPTION Exception section END;
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;
Executing In standalone statement: EXECUTE procedure(parameter list); Called from another PL/SQL block: … procedure(parameter list);
Deleting DROP PROCEDURE procedure-name;
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];
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;
Example cont’d SELECT course_name, FindCourse(course_name) AS course_id FROM courses WHERE subject = 'Mathematics';
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.
MS SQL Server Stored Procedure Example To create: CREATE PROCEDURE getAddress (@City VARCHAR(30)) AS BEGIN SELECT * FROM Staff WHERE City = @City; END; GO To Execute: EXEC getAddress @City = ‘Houston’;
MS SQL Server Function Example To create: CREATE FUNCTION getSite ( @site_id INT ) RETURNS VARCHAR(50) AS BEGIN DECLARE @site_name VARCHAR(50); IF @site_id < 10 SET @site_name = ‘UHD.edu'; ELSE SET @site_name = ‘Houston.gov'; RETURN @site_name; END; To execute: SELECT dbo.getSite(8);
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
Trigger Format
A BEFORE Trigger
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;
INSTEAD OF Trigger Views are not updateable if there are more than two base tables INSTEAD OF Triggers are used to update views
Trigger Privilege Must be the owner of the table Or have been granted the TRIGGER privilege on the table
Trigger Advantages and Disadvantages Reduce redundancy Simply modifications Increase security Improve integrity Improve processing power … Performance overhead Cascading effects