Winter 2006Keller, Ullman, Cushing10–1 Modification to Views Via Triggers Oracle allows us to “intercept” a modification to a view through an instead-of.

Slides:



Advertisements
Similar presentations
BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
Advertisements

AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
PL/SQL. Introduction to PL/SQL PL/SQL is the procedure extension to Oracle SQL. It is used to access an Oracle database from various environments (e.g.
Stored Procedure Language Stored Procedure Overview Stored Procedure is a function in a shared library accessible to the database server can also write.
Chapter 4B: More Advanced PL/SQL Programming
Fall 2001Arthur Keller – CS 18011–1 Schedule Oct. 30 (T) Embedded SQL. u Read Section 8.1. u Assignment 5 due. Not accepted late. u Project Part 4 due.
Fall 2001Arthur Keller – CS 18010–1 Schedule Oct. 25 (TH) More Constraints, Triggers. u Read Sections Oct. 30 (T) Embedded SQL. u Read Section.
Winter 2002Arthur Keller – CS 1808–1 Schedule Today: Jan. 29 (T) u Modifications, Schemas, Views. u Read Sections Assignment 3 due. Jan. 31 (TH)
Winter 2002Arthur Keller – CS 18010–1 Schedule Today: Feb. 5 (T) u Triggers, PL/SQL. u Read Sections 7.4, 8.2. Assignment 4 due. Feb. 7 (TH) u PL/SQL,
Winter 2002Arthur Keller – CS 1809–1 Schedule Today: Jan. 31 (TH) u Constraints. u Read Sections , Project Part 3 due. Feb. 5 (T) u Triggers,
Winter 2002Judy Cushing8–1 Schedule Jan. 30 (Wed) u Modifications, Schemas, Views. Read Sections This Week (Feb 4ff) u Constraints Read Sections.
CPSC-608 Database Systems Fall 2011 Instructor: Jianer Chen Office: HRBB 315C Phone: Notes #3.
1 SQL/PSM Procedures Stored in the Database General-Purpose Programming.
Winter 2002Arthur Keller – CS 18011–1 Schedule Today: Feb. 7 (TH) u PL/SQL, Embedded SQL, CLI, JDBC. u Read Sections 8.1, Feb. 12 (T) Advising.
Winter 2002Arthur Keller – CS 1807–1 Schedule Today: Jan. 24 (TH) u Subqueries, Grouping and Aggregation. u Read Sections Project Part 2 due.
1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL.
1 PL/SQL Oracle’s Version of Triggers and PSM. 2 PL/SQL uOracle uses a variant of SQL/PSM which it calls PL/SQL. uPL/SQL not only allows you to create.
DB Modifications Modification = insert + delete + update. Insertion of a Tuple INSERT INTO relation VALUES (list of values). Inserts the tuple = list of.
1 SQL Programming Embedded SQL Call-Level Interface Java Database Connectivity Persistent Stored Modules.
Cursors in Pl/SQL Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL.
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Triggers, PL/SQL, embedded SQL, JDBC.
Winter 2006Keller Ullman Cushing8–1 Turning in Assignments Please turn in hard copy (use only in the direst of circumstances). I am not your secretary.
Constraints on Relations Foreign Keys Local and Global Constraints Triggers Following lecture slides are modified from Jeff Ullman’s slides
Winter 2006Keller, Ullman, Cushing9–1 Constraints Commercial relational systems allow much more “fine-tuning” of constraints than do the modeling languages.
1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL.
Winter 2006 Keller, Ullman, Cushing 11–1 Embedded SQL Add to a conventional programming language (C in our examples) certain statements that represent.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 8 Advanced SQL.
1 Real SQL Programming - 2 Persistent Stored Modules (PSM) PL/SQL Embedded SQL These slides are reused from Jeffrey Ullman’s class with the author’s permission.
Databases 1 9th lecture. Main topic: Oracle PL/SQL What is PL/SQL? ▫Procedural Langauge extension for standard SQL.. PL/SQL not only allows you to create.
Introduction to PL/SQL. Main topic: Oracle PL/SQL What is PL/SQL? ▫Procedural Langauge extension for standard SQL.. PL/SQL not only allows you to create.
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL.
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Stored Procedure used in PosgreSQL.
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
Himanshu GuptaCSE 532-SQL-1 SQL. Himanshu GuptaCSE 532-SQL-2 Why SQL? SQL is a very-high-level language, in which the programmer is able to avoid specifying.
SCUHolliday - coen 1787–1 Schedule Today: u Subqueries, Grouping and Aggregation. u Read Sections Next u Modifications, Schemas, Views. u Read.
SCU Fall 2002JoAnne Holliday10–1 Schedule Today u Triggers, Procedures, PL/SQL. u Read Sections , 8.1, 8.5. Next u Transaction concepts, security.
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Embedded SQL, JDBC. u Read Sections.
1 Database Design: DBS CB, 2 nd Edition SQL in a Server Environment: Stored Procedure & Embedded SQL Ch. 9.3, 9.4.
1 Introduction to Database Systems, CS420 SQL Persistent Stored Modules (PSM) – Stored Procedure.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
1 Lecture 11 PL/SQL Slides from
CPSC-310 Database Systems
Introduction to Database Systems, CS420
User Defined Functions and Triggers Tutorial
Slides are reused by the approval of Jeffrey Ullman’s
CMSC-461 Database Management Systems
Foreign Keys Local and Global Constraints Triggers
Schedule Today: Next After that Subqueries, Grouping and Aggregation.
Introduction to Database Systems, CS420
CPSC-608 Database Systems
CPSC-608 Database Systems
CS4222 Principles of Database System
CPSC-310 Database Systems
Database Models Relational Model
CPSC-310 Database Systems
CPSC-310 Database Systems
Stored Procedure used in PosgreSQL
Persistent Stored Modules (PSM) PL/SQL Embedded SQL
CMSC-461 Database Management Systems
CPSC-608 Database Systems
Modification to Views Via Triggers
CPSC-608 Database Systems
Stored Procedure Language
Instructor: Zhe He Department of Computer Science
Select-From-Where Statements Multirelation Queries Subqueries
Presentation transcript:

Winter 2006Keller, Ullman, Cushing10–1 Modification to Views Via Triggers Oracle allows us to “intercept” a modification to a view through an instead-of trigger. Example Likes(drinker, beer) Sells(bar, beer, price) Frequents(drinker, bar) CREATE VIEW Synergy AS SELECT Likes.drinker, Likes.beer, Sells.bar FROM Likes, Sells, Frequents WHERE Likes.drinker = Frequents.drinker AND Likes.beer = Sells.beer AND Sells.bar = Frequents.bar;

Winter 2006Keller, Ullman, Cushing10–2 CREATE TRIGGER ViewTrig INSTEAD OF INSERT ON Synergy FOR EACH ROW BEGIN INSERT INTO Likes VALUES( :new.drinker, :new.beer); INSERT INTO Sells(bar, beer) VALUES(:new.bar, :new.beer); INSERT INTO Frequents VALUES( :new.drinker, :new.bar); END;. run

Winter 2006Keller, Ullman, Cushing10–3 SQL Triggers Read in text. Some differences, including: 1. The Oracle restriction about not modifying the relation of the trigger or other relations linked to it by constraints is not present in SQL (but Oracle is real; SQL is paper). 2. The action in SQL is a list of (restricted) SQL statements, not a PL/SQL statement.

Winter 2006Keller, Ullman, Cushing10–4 PL/SQL Oracle’s version of PSM (Persistent, Stored Modules).  Use via sqlplus. A compromise between completely procedural programming and SQL’s very high-level, but limited statements. Allows local variables, loops, procedures, examination of relations one tuple at a time. Rough form: DECLARE declarations BEGIN executable statements END;. run; DECLARE portion is optional. Dot and run (or a slash in place of run; ) are needed to end the statement and execute it.

Winter 2006Keller, Ullman, Cushing10–5 Simplest Form: Sequence of Modifications Likes(drinker, beer) BEGIN INSERT INTO Likes VALUES('Sally', 'Bud'); DELETE FROM Likes WHERE drinker = 'Fred' AND beer = 'Miller'; END;. run;

Winter 2006Keller, Ullman, Cushing10–6 Procedures Stored database objects that use a PL/SQL statement in their body. Procedure Declarations CREATE OR REPLACE PROCEDURE ( ) AS BEGIN END;. run;

Winter 2006Keller, Ullman, Cushing10–7 Argument list has name-mode-type triples. u Mode: IN, OUT, or IN OUT for read-only, write-only, read/write, respectively.  Types: standard SQL + generic types like NUMBER = any integer or real type. u Since types in procedures must match their types in the DB schema, you should generally use an expression of the form relation.attribute %TYPE to capture the type correctly.

Winter 2006Keller, Ullman, Cushing10–8 Example A procedure to take a beer and price and add it to Joe’s menu. Sells(bar, beer, price) CREATE PROCEDURE joeMenu( b IN Sells.beer %TYPE, p IN Sells.price %TYPE ) AS BEGIN INSERT INTO Sells VALUES('Joe''s Bar', b, p); END;. run; Note “ run ” only stores the procedure; it doesn’t execute the procedure.

Winter 2006Keller, Ullman, Cushing10–9 Invoking Procedures A procedure call may appear in the body of a PL/SQL statement. Example: BEGIN joeMenu('Bud', 2.50); joeMenu('MooseDrool', 5.00); END;. run;

Winter 2006Keller, Ullman, Cushing10–10 Assignment Assign expressions to declared variables with :=. Branches IF THEN ELSE END IF; But in nests, use ELSIF in place of ELSE IF. Loops LOOP... EXIT WHEN... END LOOP;

Winter 2006Keller, Ullman, Cushing10–11 Queries in PL/SQL 1.Single-row selects allow retrieval into a variable of the result of a query that is guaranteed to produce one tuple. 2.Cursors allow the retrieval of many tuples, with the cursor and a loop used to process each in turn.

Winter 2006Keller, Ullman, Cushing10–12 Single-Row Select Select-from-where in PL/SQL must have an INTO clause listing variables into which a tuple can be placed. It is an error if the select-from-where returns more than one tuple; you should have used a cursor. Example Find the price Joe charges for Bud (and drop it on the floor). Sells(bar, beer, price) DECLARE p Sells.price %TYPE; BEGIN SELECT price INTO p FROM Sells WHERE bar = 'Joe''s Bar' AND beer = 'Bud'; END;. run

Winter 2006Keller, Ullman, Cushing10–13 Functions (PostgreSQL Version) Server-side functions can be written in several languages: SQL PL/PGSQL PL/TCL PL/Perl C

Winter 2006Keller, Ullman, Cushing10–14 SQL Functions (PostgreSQL Version) Like Oracle stored procedures. CREATE FUNCTION requires the following information: Function name Number of function arguments Data type of each argument Function return type Function action Language used by the function action

Winter 2006Keller, Ullman, Cushing10–15 Example A simple SQL function to convert a temperature from Fahrenheit to centigrade degrees. CREATE FUNCTION ftoc(float) RETURNS float AS 'SELECT ($ ) * 5.0 / 9.0;' LANGUAGE 'sql'; SELECT ftoc(68); ftoc (1 row)

Winter 2006Keller, Ullman, Cushing10–16 Functions (Continued) SQL functions can return multiple values using SETOF. Function actions can also contain INSERTs, UPDATEs, and DELETEs as well as multiple queries separated by semicolons. Arguments: $1 is automatically replaced by the first argument of the function call. $2 is the second argument, etc.

Winter 2006Keller, Ullman, Cushing10–17 Example SQL server-side function to compute a sales tax. CREATE FUNCTION tax(numeric) RETURNS numeric AS 'SELECT ($1 * 0.06::numeric(8,2))::numeric(8,2);' LANGUAGE 'sql'; SELECT tax(100); tax (1 row) Notice the casts to NUMERIC(8,2) using the double- colon form of type casting, rather than CAST.

Winter 2006Keller, Ullman, Cushing10–18 Server Side Functions in SQL Queries CREATE TABLE part ( part_id INTEGER, name CHAR(10), cost NUMERIC(8,2), weight FLOAT ); INSERT INTO part VALUES (637, 'cable', 14.29, 5); INSERT INTO part VALUES (638, 'sticker', 0.84, 1); INSERT INTO part VALUES (639, 'bulb', 3.68, 3); SELECT part_id, name, cost, tax(cost), cost+tax(cost) AS total FROM part ORDER BY part_id; part_id | name | cost | tax | total | cable | | 0.86 | | sticker | 0.84 | 0.05 | | bulb | 3.68 | 0.22 | 3.90 (3 rows)

Winter 2006Keller, Ullman, Cushing10–19 Example: Shipping CREATE FUNCTION shipping(numeric) RETURNS numeric AS 'SELECT CASE WHEN $1 < 2 THEN CAST(3.00 AS numeric(8,2)) WHEN $1 >= 2 AND $1 < 4 THEN CAST(5.00 AS numeric(8,2)) WHEN $1 >= 4 THEN CAST(6.00 AS numeric(8,2)) END;' LANGUAGE 'sql'; SELECT part_id, trim(name) AS name, cost, tax(cost), cost+tax(cost) AS subtotal, shipping(weight), cost+tax(cost)+shipping(weight) AS total FROM part ORDER BY part_id; part_id | name | cost | tax | subtotal | shipping | total | cable | | 0.86 | | 6.00 | | sticker | 0.84 | 0.05 | 0.89 | 3.00 | | bulb | 3.68 | 0.22 | 3.90 | 5.00 | 8.90 (3 rows)

Winter 2006Keller, Ullman, Cushing10–20 Triggers (PostgreSQL Version) Create a function for states that uses the new RECORD variable to perform the following actions: Reject a state code that is not exactly two alphabetic characters Reject a state name that contains nonalphabetic characters Reject a state name less than three characters in length Uppercase the state code Capitalize the state name

Winter 2006Keller, Ullman, Cushing10–21 Example Function CREATE FUNCTION trigger_insert_update_statename() RETURNS opaque AS 'BEGIN IF new.code ! ''[A-Za-z][A-Za-z]$'' THEN RAISE EXCEPTION '' State code must be two alphabetic characters.''; END IF; IF new.name ! ''[A-Za-z ]*$'' THEN RAISE EXCEPTION '' State name must be only alphabetic characters.''; END IF; IF length(trim(new.name)) < 3 THEN RAISE EXCEPTION '' State name must longer than two characters.''; END IF; new.code = upper(new.code); -- uppercase statename.code new.name = initcap(new.name); -- capitalize statename.name RETURN new; END;' LANGUAGE 'plpgsql';

Winter 2006Keller, Ullman, Cushing10–22 Trigger (PostgreSQL Version) CREATE TRIGGER trigger_statename BEFORE INSERT OR UPDATE ON statename FOR EACH ROW EXECUTE PROCEDURE trigger_insert_update_statename() ;

Winter 2006Keller, Ullman, Cushing10–23 Example Execution INSERT INTO statename VALUES ('a', 'alabama'); ERROR: State code must be two alphabetic characters. INSERT INTO statename VALUES ('al', 'alabama2'); ERROR: State name must be only alphabetic characters. INSERT INTO statename VALUES ('al', 'al'); ERROR: State name must longer than two characters. INSERT INTO statename VALUES ('al', 'alabama'); INSERT SELECT * FROM statename; code | name AL | Alabama (1 row)

Winter 2006Keller, Ullman, Cushing10–24 Cursors Declare by: CURSOR IS select-from-where statement Cursor gets each tuple from the relation produced by the select-from- where, in turn, using a fetch statement in a loop.  Fetch statement: FETCH INTO variable list ; Break the loop by a statement of the form: EXIT WHEN %NOTFOUND; u True when there are no more tuples to get. Open and close the cursor with OPEN and CLOSE.

Winter 2006Keller, Ullman, Cushing10–25 Example A procedure that examines the menu for Joe’s Bar and raises by $1.00 all prices that are less than $3.00. Sells(bar, beer, price) This simple price-change algorithm can be implemented by a single UPDATE statement, but more complicated price changes could not.

Winter 2006Keller, Ullman, Cushing10–26 CREATE PROCEDURE joeGouge() AS theBeer Sells.beer%TYPE; thePrice Sells.price%TYPE; CURSOR c IS SELECT beer, price FROM Sells WHERE bar = 'Joe''s bar'; BEGIN OPEN c; LOOP FETCH c INTO theBeer, thePrice; EXIT WHEN c%NOTFOUND; IF thePrice < 3.00 THEN UDPATE Sells SET price = thePrice WHERE bar = 'Joe''s Bar' AND beer = theBeer; END IF; END LOOP; CLOSE c; END;. run

Winter 2006Keller, Ullman, Cushing10–27 Row Types Anything (e.g., cursors, table names) that has a tuple type can have its type captured with %ROWTYPE. We can create temporary variables that have tuple types and access their components with dot. Handy when we deal with tuples with many attributes.

Winter 2006Keller, Ullman, Cushing10–28 Example The same procedure with a tuple variable bp. CREATE PROCEDURE joeGouge() AS CURSOR c IS SELECT beer, price FROM Sells WHERE bar = 'Joe''s bar'; bp c%ROWTYPE; BEGIN OPEN c; LOOP FETCH c INTO bp; EXIT WHEN c%NOTFOUND; IF bp.price < 3.00 THEN UDPATE Sells SET price = bp.price WHERE bar = 'Joe''s Bar' AND beer = bp.beer; END IF; END LOOP; CLOSE c; END;. run