1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL.

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.
Chapter 9 SQL in a Server Environment Call-Level Interface Java Database Connectivity PHP.
CSC343 – Introduction to databases – A. Vaisman1 Database Application Development.
UJeffrey D. Ullman uAnfang von: CS145 - Herbst Stanford University uOnline unter: Folien mit weißem Hintergrund wurden.
1 Combining SQL and Conventional Programming Languages Source: slides by Jeffrey Ullman.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Introduction to SQL Programming Techniques.
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.
1 Chapter 7 System Aspects of SQL uSQL in a Programming Environment uTransactions uAuthorization.
Fall 2001Arthur Keller – CS 18010–1 Schedule Oct. 25 (TH) More Constraints, Triggers. u Read Sections Oct. 30 (T) Embedded SQL. u Read Section.
End of SQL: Triggers, Impedance Mismatch and Transactions February 6 th, 2004.
1 More SQL Defining a Database Schema Views. 2 Defining a Database Schema uA database schema comprises declarations for the relations (“tables”) of the.
M.P. Johnson, DBMS, Stern/NYU, Sp20041 C : Database Management Systems Lecture #19 Matthew P. Johnson Stern School of Business, NYU Spring, 2004.
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.
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.
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.
1 SQL Programming Embedded SQL Call-Level Interface Java Database Connectivity Persistent Stored Modules.
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.
1 SQL/PSM Procedures Stored in the Database General-Purpose Programming.
Announcements Read JDBC Project Step 5, due Monday.
1 Real SQL Programming Embedded SQL Call-Level Interface Java Database Connectivity.
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.
Winter 2006Keller, Ullman, Cushing9–1 Constraints Commercial relational systems allow much more “fine-tuning” of constraints than do the modeling languages.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
Advanced SQL: Cursors & Stored Procedures
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL.
1 Real SQL Programming Embedded SQL Java Database Connectivity Stored Procedures.
Winter 2006 Keller, Ullman, Cushing 11–1 Embedded SQL Add to a conventional programming language (C in our examples) certain statements that represent.
SQL in a Programming Environment CIS 4301 Lecture Notes Lecture /11/2006.
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.
1 CS 430 Database Theory Winter 2005 Lecture 14: Additional SQL Topics.
1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL.
Different Constraint Types Type Where Declared When activated Guaranteed to hold? Attribute with attribute on insertion not if CHECK or update subquery.
SQL Programming SQL in Application Programs
Constraining Attribute Values Constrain invalid values –NOT NULL –gender CHAR(1) CHECK (gender IN (‘F’, ‘M’)) –MovieName CHAR(30) CHECK (MovieName IN (SELECT.
SCU Fall 2002JoAnne Holliday10–1 Schedule Today u Triggers, Procedures, PL/SQL. u Read Sections , 8.1, 8.5. Next u Transaction concepts, security.
1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL.
Chapter 8 Advanced SQL Pearson Education © Chapter 8 - Objectives How to use the SQL programming language How to use SQL cursors How to create stored.
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 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL (modified 11/11/2013)
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.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
SQL in the real world 1. The Three-Tier Architecture of Database Applications browser network HTTP Web server Application server Database server database.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Application Development Chapter 6.
SQL in the real world 1. The SQL Client-Server Interactions SQL-clientSQL-server Environment SQL-agent Module Connection Session Current catalog and schema.
1 Lecture 11 PL/SQL Slides from
SQL Environment.
Introduction to Database Systems, CS420
CMSC-461 Database Management Systems
Foreign Keys Local and Global Constraints Triggers
Database Application Development
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
Modification to Views Via Triggers
Embedded SQL Chapter 8.
Database Application Development
Presentation transcript:

1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL

2 SQL in Real Programs uWe have seen only how SQL is used at the generic query interface --- an environment where we sit at a terminal and ask queries of a database. uReality is almost always different: conventional programs interacting with SQL.

3 Options 1.Code in a specialized language is stored in the database itself (e.g., PSM, PL/SQL). 2.SQL statements are embedded in a host language (e.g., C). 3.Connection tools are used to allow a conventional language to access a database (e.g., CLI, JDBC, PHP/DB).

4 Stored Procedures uPSM, or “persistent stored modules,” allows us to store procedures as database schema elements. uPSM = a mixture of conventional statements (if, while, etc.) and SQL. uLets us do things we cannot do in SQL alone.

5 Basic PSM Form CREATE PROCEDURE ( ) ; uFunction alternative: CREATE FUNCTION ( ) RETURNS

6 Parameters in PSM uUnlike the usual name-type pairs in languages like C, PSM uses mode- name-type triples, where the mode can be: wIN = procedure uses value, does not change value. wOUT = procedure changes, does not use. wINOUT = both.

7 Example: Stored Procedure uLet’s write a procedure that takes two arguments b and p, and adds a tuple to Sells(bar, beer, price) that has bar = ’Joe’’s Bar’, beer = b, and price = p. wUsed by Joe to add to his menu more easily.

8 The Procedure CREATE PROCEDURE JoeMenu ( INbCHAR(20), IN pREAL ) INSERT INTO Sells VALUES(’Joe’’s Bar’, b, p); Parameters are both read-only, not changed The body --- a single insertion

9 Invoking Procedures uUse SQL/PSM statement CALL, with the name of the desired procedure and arguments. uExample: CALL JoeMenu(’Moosedrool’, 5.00); uFunctions used in SQL expressions wherever a value of their return type is appropriate.

10 Kinds of PSM statements – (1) uRETURN sets the return value of a function. wUnlike C, etc., RETURN does not terminate function execution. uDECLARE used to declare local variables. uBEGIN... END for groups of statements. wSeparate statements by semicolons.

11 Kinds of PSM Statements – (2) uAssignment statements: SET = ;  Example: SET b = ’Bud’; uStatement labels: give a statement a label by prefixing a name and a colon.

12 IF Statements uSimplest form: IF THEN END IF; uAdd ELSE if desired, as IF... THEN... ELSE... END IF; uAdd additional cases by ELSEIF : IF … THEN … ELSEIF … THEN … ELSEIF … THEN … ELSE … END IF;

13 Example: IF uLet’s rate bars by how many customers they have, based on Frequents(drinker,bar). w<100 customers: ‘unpopular’. w customers: ‘average’. w>= 200 customers: ‘popular’. uFunction Rate(b) rates bar b.

14 Example: IF (continued) CREATE FUNCTION Rate (IN b CHAR(20) ) RETURNS CHAR(10) DECLARE cust INTEGER; BEGIN SET cust = (SELECT COUNT(*) FROM Frequents WHERE bar = b); IF cust < 100 THEN RETURN ’unpopular’ ELSEIF cust < 200 THEN RETURN ’average’ ELSE RETURN ’popular’ END IF; END; Number of customers of bar b Return occurs here, not at one of the RETURN statements Nested IF statement

15 Loops uBasic form: : LOOP END LOOP; uExit from a loop by: LEAVE

16 Example: Exiting a Loop loop1: LOOP... LEAVE loop1;... END LOOP; If this statement is executed... Control winds up here

17 Other Loop Forms uWHILE DO END WHILE; uREPEAT UNTIL END REPEAT;

18 Queries uGeneral SELECT-FROM-WHERE queries are not permitted in PSM. uThere are three ways to get the effect of a query: 1.Queries producing one value can be the expression in an assignment. 2.Single-row SELECT... INTO. 3.Cursors.

19 Example: Assignment/Query uUsing local variable p and Sells(bar, beer, price), we can get the price Joe charges for Bud by: SET p = (SELECT price FROM Sells WHERE bar = ’Joe’’s Bar’ AND beer = ’Bud’);

20 SELECT... INTO uAnother way to get the value of a query that returns one tuple is by placing INTO after the SELECT clause. uExample: SELECT price INTO p FROM Sells WHERE bar = ’Joe’’s Bar’ AND beer = ’Bud’;

21 Cursors uA cursor is essentially a tuple-variable that ranges over all tuples in the result of some query. uDeclare a cursor c by: DECLARE c CURSOR FOR ;

22 Opening and Closing Cursors uTo use cursor c, we must issue the command: OPEN c; wThe query of c is evaluated, and c is set to point to the first tuple of the result. uWhen finished with c, issue command: CLOSE c;

23 Fetching Tuples From a Cursor uTo get the next tuple from cursor c, issue command: FETCH FROM c INTO x1, x2,…,xn ; uThe x ’s are a list of variables, one for each component of the tuples referred to by c. uc is moved automatically to the next tuple.

24 Breaking Cursor Loops – (1) uThe usual way to use a cursor is to create a loop with a FETCH statement, and do something with each tuple fetched. uA tricky point is how we get out of the loop when the cursor has no more tuples to deliver.

25 Breaking Cursor Loops – (2) uEach SQL operation returns a status, which is a 5-digit character string. wFor example, = “Everything OK,” and = “Failed to find a tuple.” uIn PSM, we can get the value of the status in a variable called SQLSTATE.

26 Breaking Cursor Loops – (3) uWe may declare a condition, which is a boolean variable that is true if and only if SQLSTATE has a particular value.  Example: We can declare condition NotFound to represent by: DECLARE NotFound CONDITION FOR SQLSTATE ’02000’;

27 Breaking Cursor Loops – (4) uThe structure of a cursor loop is thus: cursorLoop: LOOP … FETCH c INTO … ; IF NotFound THEN LEAVE cursorLoop; END IF; … END LOOP;

28 Example: Cursor uLet’s write a procedure that examines Sells(bar, beer, price), and raises by $1 the price of all beers at Joe’s Bar that are under $3. wYes, we could write this as a simple UPDATE, but the details are instructive anyway.

29 The Needed Declarations CREATE PROCEDURE JoeGouge( ) DECLARE theBeer CHAR(20); DECLARE thePrice REAL; DECLARE NotFound CONDITION FOR SQLSTATE ’02000’; DECLARE c CURSOR FOR (SELECT beer, price FROM Sells WHERE bar = ’Joe’’s Bar’); Used to hold beer-price pairs when fetching through cursor c Returns Joe’s menu

30 The Procedure Body BEGIN OPEN c; menuLoop: LOOP FETCH c INTO theBeer, thePrice; IF NotFound THEN LEAVE menuLoop END IF; IF thePrice < 3.00 THEN UPDATE Sells SET price = thePrice WHERE bar = ’Joe’’s Bar’ AND beer = theBeer; END IF; END LOOP; CLOSE c; END; Check if the recent FETCH failed to get a tuple If Joe charges less than $3 for the beer, raise its price at Joe’s Bar by $1.

31 PL/SQL uOracle uses a variant of SQL/PSM which it calls PL/SQL. uPL/SQL not only allows you to create and store procedures or functions, but it can be run from the generic query interface (sqlplus), like any SQL statement. uTriggers are a part of PL/SQL.

32 Trigger Differences uCompared with SQL standard triggers, Oracle has the following differences: 1.Action is a PL/SQL statement. 2.New/old tuples referenced automatically. 3.Strong constraints on trigger actions designed to make certain you can’t fire off an infinite sequence of triggers. uSee on-line or-triggers.html document.

33 SQLPlus uIn addition to stored procedures, one can write a PL/SQL statement that looks like the body of a procedure, but is executed once, like any SQL statement typed to the generic interface. wOracle calls the generic interface “sqlplus.” wPL/SQL is really the “plus.”

34 Form of PL/SQL Statements DECLARE BEGIN END;. run uThe DECLARE section is optional.

35 Form of PL/SQL Procedure CREATE OR REPLACE PROCEDURE ( ) AS BEGIN END;. run Notice AS needed here Needed to store procedure in database; does not really run it.

36 PL/SQL Declarations and Assignments uThe word DECLARE does not appear in front of each local declaration. wJust use the variable name and its type. uThere is no word SET in assignments, and := is used in place of =. wExample: x := y;

37 PL/SQL Procedure Parameters uThere are several differences in the forms of PL/SQL argument or local- variable declarations, compared with the SQL/PSM standard: 1.Order is name-mode-type, not mode- name-type. 2.INOUT is replaced by IN OUT in PL/SQL. 3.Several new types.

38 PL/SQL Types uIn addition to the SQL types, NUMBER can be used to mean INT or REAL, as appropriate. uYou can refer to the type of attribute x of relation R by R.x%TYPE. wUseful to avoid type mismatches. wAlso, R%ROWTYPE is a tuple whose components have the types of R’s attributes.

39 Example:JoeMenu uRecall the procedure JoeMenu(b,p) that adds beer b at price p to the beers sold by Joe (in relation Sells). uHere is the PL/SQL version.

40 Procedure JoeMenu in PL/SQL CREATE OR REPLACE 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 Notice these types will be suitable for the intended uses of b and p.

41 PL/SQL Branching Statements uLike IF … in SQL/PSM, but: uUse ELSIF in place of ELSEIF. uViz.: IF … THEN … ELSIF … THEN … ELSIF … THEN … ELSE … END IF;

42 PL/SQL Loops uLOOP … END LOOP as in SQL/PSM. uInstead of LEAVE …, PL/SQL uses EXIT WHEN uAnd when the condition is that cursor c has found no tuple, we can write c%NOTFOUND as the condition.

43 PL/SQL Cursors uThe form of a PL/SQL cursor declaration is: CURSOR IS ; uTo fetch from cursor c, say: FETCH c INTO ;

44 Example: JoeGouge() in PL/SQL uRecall JoeGouge() sends a cursor through the Joe’s-Bar portion of Sells, and raises by $1 the price of each beer Joe’s Bar sells, if that price was initially under $3.

45 Example: JoeGouge() Declarations CREATE OR REPLACE PROCEDURE JoeGouge() AS theBeer Sells.beer%TYPE; thePrice Sells.price%TYPE; CURSOR c IS SELECT beer, price FROM Sells WHERE bar = ’Joe’’s Bar’;

46 Example: JoeGouge() Body BEGIN OPEN c; LOOP FETCH c INTO theBeer, thePrice; EXIT WHEN c%NOTFOUND; IF thePrice < 3.00 THEN UPDATE Sells SET price = thePrice ; WHERE bar = ’Joe’’s Bar’ AND beer = theBeer; END IF; END LOOP; CLOSE c; END; How PL/SQL breaks a cursor loop Note this is a SET clause in an UPDATE, not an assignment. PL/SQL uses := for assignments.

47 Tuple-Valued Variables uPL/SQL allows a variable x to have a tuple type. ux R%ROWTYPE gives x the type of R’s tuples. uR could be either a relation or a cursor. ux.a gives the value of the component for attribute a in the tuple x.

48 Example: Tuple Type uRepeat of JoeGouge() declarations with variable bp of type beer-price pairs. CREATE OR REPLACE PROCEDURE JoeGouge() AS CURSOR c IS SELECT beer, price FROM Sells WHERE bar = ’Joe’’s Bar’; bp c%ROWTYPE;

49 JoeGouge() Body Using bp BEGIN OPEN c; LOOP FETCH c INTO bp; EXIT WHEN c%NOTFOUND; IF bp.price < 3.00 THEN UPDATE Sells SET price = bp.price WHERE bar = ’Joe’’s Bar’ AND beer =bp.beer; END IF; END LOOP; CLOSE c; END; Components of bp are obtained with a dot and the attribute name

50 Embedded SQL uKey idea: A preprocessor turns SQL statements into procedure calls that fit with the surrounding host-language code. uAll embedded SQL statements begin with EXEC SQL, so the preprocessor can find them easily.

51 Shared Variables uTo connect SQL and the host-language program, the two parts must share some variables. uDeclarations of shared variables are bracketed by: EXEC SQL BEGIN DECLARE SECTION; EXEC SQL END DECLARE SECTION; Always needed

52 Use of Shared Variables uIn SQL, the shared variables must be preceded by a colon. wThey may be used as constants provided by the host-language program. wThey may get values from SQL statements and pass those values to the host- language program. uIn the host language, shared variables behave like any other variable.

53 Example: Looking Up Prices uWe’ll use C with embedded SQL to sketch the important parts of a function that obtains a beer and a bar, and looks up the price of that beer at that bar. uAssumes database has our usual Sells(bar, beer, price) relation.

54 Example: C Plus SQL EXEC SQL BEGIN DECLARE SECTION; char theBar[21], theBeer[21]; float thePrice; EXEC SQL END DECLARE SECTION; /* obtain values for theBar and theBeer */ EXEC SQL SELECT price INTO :thePrice FROM Sells WHERE bar = :theBar AND beer = :theBeer; /* do something with thePrice */ Note 21-char arrays needed for 20 chars + endmarker SELECT-INTO as in PSM

55 Embedded Queries uEmbedded SQL has the same limitations as PSM regarding queries: wSELECT-INTO for a query guaranteed to produce a single tuple. wOtherwise, you have to use a cursor. Small syntactic differences, but the key ideas are the same.

56 Cursor Statements uDeclare a cursor c with: EXEC SQL DECLARE c CURSOR FOR ; uOpen and close cursor c with: EXEC SQL OPEN CURSOR c; EXEC SQL CLOSE CURSOR c; uFetch from c by: EXEC SQL FETCH c INTO ; wMacro NOT FOUND is true if and only if the FETCH fails to find a tuple.

57 Example: Print Joe’s Menu uLet’s write C + SQL to print Joe’s menu – the list of beer-price pairs that we find in Sells(bar, beer, price) with bar = Joe’s Bar. uA cursor will visit each Sells tuple that has bar = Joe’s Bar.

58 Example: Declarations EXEC SQL BEGIN DECLARE SECTION; char theBeer[21]; float thePrice; EXEC SQL END DECLARE SECTION; EXEC SQL DECLARE c CURSOR FOR SELECT beer, price FROM Sells WHERE bar = ’Joe’’s Bar’; The cursor declaration goes outside the declare-section

59 Example: Executable Part EXEC SQL OPEN CURSOR c; while(1) { EXEC SQL FETCH c INTO :theBeer, :thePrice; if (NOT FOUND) break; /* format and print theBeer and thePrice */ } EXEC SQL CLOSE CURSOR c; The C style of breaking loops

60 Need for Dynamic SQL uMost applications use specific queries and modification statements to interact with the database. wThe DBMS compiles EXEC SQL … statements into specific procedure calls and produces an ordinary host-language program that uses a library. uWhat about sqlplus, which doesn’t know what it needs to do until it runs?

61 Dynamic SQL uPreparing a query: EXEC SQL PREPARE FROM ; uExecuting a query: EXEC SQL EXECUTE ; u“Prepare” = optimize query. uPrepare once, execute many times.

62 Example: A Generic Interface EXEC SQL BEGIN DECLARE SECTION; char query[MAX_LENGTH]; EXEC SQL END DECLARE SECTION; while(1) { /* issue SQL> prompt */ /* read user’s query into array query */ EXEC SQL PREPARE q FROM :query; EXEC SQL EXECUTE q; } q is an SQL variable representing the optimized form of whatever statement is typed into :query

63 Execute-Immediate uIf we are only going to execute the query once, we can combine the PREPARE and EXECUTE steps into one. uUse: EXEC SQL EXECUTE IMMEDIATE ;

64 Example: Generic Interface Again EXEC SQL BEGIN DECLARE SECTION; char query[MAX_LENGTH]; EXEC SQL END DECLARE SECTION; while(1) { /* issue SQL> prompt */ /* read user’s query into array query */ EXEC SQL EXECUTE IMMEDIATE :query; }