Fall 2001Arthur Keller – CS 18010–1 Schedule Oct. 25 (TH) More Constraints, Triggers. u Read Sections 7.3-7.4. Oct. 30 (T) Embedded SQL. u Read Section.

Slides:



Advertisements
Similar presentations
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Advertisements

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.
Winter 2002Arthur Keller – CS 1806–1 Schedule Today: Jan. 22 (T) u SQL Queries. u Read Sections Assignment 2 due. Jan. 24 (TH) u Subqueries, Grouping.
Chapter 7 Notes on Foreign Keys Local and Global Constraints Triggers.
Triggers. Triggers: Motivation Assertions are powerful, but the DBMS often can’t tell when they need to be checked. Attribute- and tuple-based checks.
Constraints and Triggers Foreign Keys Local and Global Constraints Triggers.
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 1808–1 Schedule Today Oct. 18 (TH) Schemas, Views. u Read Sections u Project Part 3 extended to Oct. 23 (T). Oct.
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,
CPSC-608 Database Systems Fall 2011 Instructor: Jianer Chen Office: HRBB 315C Phone: Notes #4.
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
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.
Fall 2001Arthur Keller – CS 1809–1 Schedule Today Oct. 23 (T) Constraints. u Read Sections Assignment 4 due. Project Part 3 due Oct. 24 (W). Oct.
Winter 2002Arthur Keller – CS 1807–1 Schedule Today: Jan. 24 (TH) u Subqueries, Grouping and Aggregation. u Read Sections Project Part 2 due.
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.
Triggers.
DB Modifications Modification = insert + delete + update. Insertion of a Tuple INSERT INTO relation VALUES (list of values). Inserts the tuple = list of.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
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, Cushing10–1 Modification to Views Via Triggers Oracle allows us to “intercept” a modification to a view through an instead-of.
Constraints on Relations Foreign Keys Local and Global Constraints Triggers Following lecture slides are modified from Jeff Ullman’s slides
Databases 1 Fourth lecture. Rest of SQL Defining a Database Schema Views Foreign Keys Local and Global Constraints Triggers 2.
Winter 2006Keller, Ullman, Cushing9–1 Constraints Commercial relational systems allow much more “fine-tuning” of constraints than do the modeling languages.
SCUHolliday - coen 1788–1 Schedule Today u Modifications, Schemas, Views. u Read Sections (except and 6.6.6) Next u Constraints. u Read.
1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL.
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.
Advanced SQL: Triggers & Assertions
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.
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 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.
Database Management COP4540, SCS, FIU Database Trigger.
Chapter 7: Constraints and Triggers Foreign Keys Local and Global Constraints Triggers 1.
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Embedded SQL, JDBC. u Read Sections.
1 Introduction to Database Systems, CS420 SQL Views and Indexes.
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 Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
1 Lecture 11 PL/SQL Slides from
CPSC-310 Database Systems
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
Introduction to Database Systems, CS420
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
CPSC-310 Database Systems
Persistent Stored Modules (PSM) PL/SQL Embedded SQL
CMSC-461 Database Management Systems
CPSC-608 Database Systems
SQL – Constraints & Triggers
CPSC-608 Database Systems
Modification to Views Via Triggers
CPSC-608 Database Systems
Instructor: Zhe He Department of Computer Science
Select-From-Where Statements Multirelation Queries Subqueries
Presentation transcript:

Fall 2001Arthur Keller – CS 18010–1 Schedule Oct. 25 (TH) More Constraints, Triggers. u Read Sections Oct. 30 (T) Embedded SQL. u Read Section 8.1. u Assignment 5 due. u Project Part 4 due. Nov. 1 (TH) Midterm u Covers material through Oct. 25 (TH) lecture and readings (Chapters 1-3, 5-7).

Fall 2001Arthur Keller – CS 18010–2 Triggers (Oracle Version) Often called event-condition-action rules. Event = a class of changes in the DB, e.g., “insertions into Beers.” Condition = a test as in a where-clause for whether or not the trigger applies. Action = one or more SQL statements. Differ from checks or SQL assertions in that: 1. Triggers invoked by the event; the system doesn’t have to figure out when a trigger could be violated. 2. Condition not available in checks.

Fall 2001Arthur Keller – CS 18010–3 Example Whenever we insert a new tuple into Sells, make sure the beer mentioned is also mentioned in Beers, and insert it (with a null manufacturer) if not. Sells(bar, beer, price) CREATE OR REPLACE TRIGGER BeerTrig AFTER INSERT ON Sells FOR EACH ROW WHEN(new.beer NOT IN (SELECT name FROM Beers)) BEGIN INSERT INTO Beers(name) VALUES(:new.beer); END;. run

Fall 2001Arthur Keller – CS 18010–4 Options 1. Can omit OR REPLACE. But if you do, it is an error if a trigger of this name exists. 2. AFTER can be BEFORE. 3.If the relation is a view, AFTER can be INSTEAD OF. u Useful for allowing “modifications” to a view; you modify the underlying relations instead. 4. INSERT can be DELETE or UPDATE OF.  Also, several conditions like INSERT ON Sells can be connected by OR. 5. FOR EACH ROW can be omitted, with an important effect: the action is done once for the relation(s) consisting of all changes.

Fall 2001Arthur Keller – CS 18010–5 Notes There are two special variables new and old, representing the new and old tuple in the change.  old makes no sense in an insert, and new makes no sense in a delete. Notice: in WHEN we use new and old without a colon, but in actions, a preceding colon is needed. The action is a PL/SQL statement.  Simplest form: surround one or more SQL statements with BEGIN and END. u However, select-from-where has a limited form.

Fall 2001Arthur Keller – CS 18010–6 Dot and run cause the definition of the trigger to be stored in the database. u Oracle triggers are part of the database schema, like tables or views. Important Oracle constraint: the action cannot change the relation that triggers the action. u Worse, the action cannot even change a relation connected to the triggering relation by a constraint, e.g., a foreign-key constraint.

Fall 2001Arthur Keller – CS 18010–7 Example Maintain a list of all the bars that raise their price for some beer by more than $1. Sells(bar, beer, price) RipoffBars(bar) CREATE TRIGGER PriceTrig AFTER UPDATE OF price ON Sells FOR EACH ROW WHEN(new.price > old.price ) BEGIN INSERT INTO RipoffBars VALUES(:new.bar); END;. run

Fall 2001Arthur Keller – CS 18010–8 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;

Fall 2001Arthur Keller – CS 18010–9 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

Fall 2001Arthur Keller – CS 18010–10 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.

Fall 2001Arthur Keller – CS 18010–11 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.

Fall 2001Arthur Keller – CS 18010–12 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;

Fall 2001Arthur Keller – CS 18010–13 Procedures Stored database objects that use a PL/SQL statement in their body. Procedure Declarations CREATE OR REPLACE PROCEDURE ( ) AS BEGIN END;. run;

Fall 2001Arthur Keller – CS 18010–14 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.

Fall 2001Arthur Keller – CS 18010–15 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.

Fall 2001Arthur Keller – CS 18010–16 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;

Fall 2001Arthur Keller – CS 18010–17 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;

Fall 2001Arthur Keller – CS 18010–18 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.

Fall 2001Arthur Keller – CS 18010–19 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

Fall 2001Arthur Keller – CS 18010–20 Functions (PostgreSQL Version) Server-side functions can be written in several languages: SQL PL/PGSQL PL/TCL PL/Perl C

Fall 2001Arthur Keller – CS 18010–21 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

Fall 2001Arthur Keller – CS 18010–22 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)

Fall 2001Arthur Keller – CS 18010–23 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.

Fall 2001Arthur Keller – CS 18010–24 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.

Fall 2001Arthur Keller – CS 18010–25 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)

Fall 2001Arthur Keller – CS 18010–26 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)

Fall 2001Arthur Keller – CS 18010–27 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

Fall 2001Arthur Keller – CS 18010–28 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';

Fall 2001Arthur Keller – CS 18010–29 Trigger (PostgreSQL Version) CREATE TRIGGER trigger_statename BEFORE INSERT OR UPDATE ON statename FOR EACH ROW EXECUTE PROCEDURE trigger_insert_update_statename() ;

Fall 2001Arthur Keller – CS 18010–30 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)