CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Chapter 8 Advanced SQL Pearson Education © Chapter 8 - Objectives u How to use the SQL programming language u How to use SQL cursors u How to create.
BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
Programming Languages and Paradigms The C Programming Language.
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.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Stored Procedure Language Stored Procedure Overview Stored Procedure is a function in a shared library accessible to the database server can also write.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Introduction to SQL Programming Techniques.
Chapter 4B: More Advanced PL/SQL Programming
Chapter 5: Loops and Files.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 10: Advanced Topics.
C++ for Engineers and Scientists Third Edition
Introduction to Structured Query Language (SQL)
UNIT II Decision Making And Branching Decision Making And Looping
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
B ASIC SQL P ROCEDURE S TRUCTURE. U NIT OBJECTIVES After completing this unit, you should be able to: Describe the structure of an SQL procedure Explain.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Constraints, Triggers and Index James Wang.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
Triggers and Stored Procedures in DB 1. Objectives Learn what triggers and stored procedures are Learn the benefits of using them Learn how DB2 implements.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Introduction to Exception Handling and Defensive Programming.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
CPS120: Introduction to Computer Science Decision Making in Programs.
Stored Procedures Week 9. Test Details Stored Procedures SQL can call code written in iSeries High Level Languages –Called stored procedures SQL has.
ISBN Chapter 8 Statement-Level Control Structures.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Bordoloi and Bock Control Structures: Iterative Control.
JavaScript, Fourth Edition
CREATING STORED PROCEDURES AND FUNCTIONS. Objectives After completing this lecture, you should be able to do the following: Differentiate between anonymous.
Loops and Files. 5.1 The Increment and Decrement Operators.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
implicit and an explicit cursor
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
DBTech VET / DBTechNet SQL Transactions Stored Procedures BY EXAMPLE: Triggers, Functions, Procedures, Cursors November 2014 Christos Skourlas
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
1 Stored Procedures in MySQL Part I. 2 Objectives SQL Vs. MySQL SP MySQL SP Parameters MySQL SP Control Structures.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
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.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
SQL Triggers, Functions & Stored Procedures Programming Operations.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
1. Advanced SQL Functions Procedural Constructs Triggers.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
PL/pgSQL
Stored Procedures.
PL/SQL.
Views, Stored Procedures, Functions, and Triggers
Error Handling Summary of the next few pages: Error Handling Cursors.
JavaScript: Control Statements.
Stored Procedure used in PosgreSQL
PL/SQL Scripting in Oracle:
Arrays, For loop While loop Do while loop
Handling Exceptions.
Chapter 8 Advanced SQL.
Information Management
Stored Procedure Language
Controlling Program Flow
Presentation transcript:

CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang

2 Stored procedures or functions Stored routines (procedures and functions) are supported in MySQL 5.0. A stored procedure is a set of SQL statements that can be stored in the server. With stored procedures, clients don't need to keep reissuing the individual statements. Instead a simple call to the stored procedure will perform the same functions. Stored routines can provide improved performance because less information exchanged between the server and the client.

3 Create Stored Routines CREATE [DEFINER = { user | CURRENT_USER }] PROCEDURE sp_name ([proc_parameter[,...]]) [characteristic...] routine_body CREATE [DEFINER = { user | CURRENT_USER }] FUNCTION sp_name ([func_parameter[,...]]) RETURNS type [characteristic...] routine_body proc_parameter: [ IN | OUT | INOUT ] param_name type func_parameter: param_name type

4 Create Stored Routines (cont.) type: Any valid MySQL data type characteristic: LANGUAGE SQL | [NOT] DETERMINISTIC | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } | SQL SECURITY { DEFINER | INVOKER } | COMMENT 'string' routine_body: Valid SQL procedure statement

5 Parameters Parameters are declared in the parentheses and they can be any valid data types. A function may have no parameter declared. Each parameter is an IN parameter by default. You can also explicitly specify a parameter to be OUT or INOUT parameter if you define a PROCEDURE (not FUNCTION). An IN parameter passes a value into a procedure. The procedure might modify the value, but the modification is not visible to the caller when the procedure returns. An OUT parameter passes a value from the procedure back to the caller. Its initial value is NULL within the procedure, and its value is visible to the caller when the procedure returns. An INOUT parameter is initialized by the caller, can be modified by the procedure, and any change made by the procedure is visible to the caller when the procedure returns. Note Specifying a parameter as IN, OUT, or INOUT is valid only for a PROCEDURE. For FUNCTION, parameters are all IN.

6 Example mysql> delimiter // mysql> CREATE PROCEDURE simpleproc (OUT param1 INT) -> BEGIN -> SELECT COUNT(*) INTO param1 FROM t; -> END; -> // Query OK, 0 rows affected (0.00 sec) mysql> delimiter ; mysql> CALL Query OK, 0 rows affected (0.00 sec) mysql> | | 3 | row in set (0.00 sec)

7 Delimiters The previous example uses the mysql client delimiter command to change the statement delimiter from ; to // while the procedure is being defined. This allows the ; delimiter used in the procedure body to be passed through to the server rather than being interpreted by mysql itself. When using the delimiter command, you should avoid the use of the backslash (“\”) character because that is the escape character for MySQL. It is unnecessary to use delimiter command when the function definition contains no internal ; statement delimiters.

8 Function Returns It is mandatory that a FUNCTION includes the RETURNS clause, which indicates the return type of the function. The function body must contain a RETURN value statement. If the RETURN statement returns a value of a different type, the value is coerced to the proper type. For example, if a function specifies an ENUM or SET value in the RETURNS clause, but the RETURN statement returns an integer, the value returned from the function is the string for the corresponding ENUM member of set of SET members.

9 Routine Characteristics Several characteristics provide information about the nature of data use by the routine. In MySQL, these characteristics are advisory only. The server does not use them to constrain what kinds of statements a routine will be allowed to execute. CONTAINS SQL: the routine does not contain statements that read or write data (this is the default characteristic). NO SQL: the routine contains no SQL statements. READS SQL DATA: the routine contains statements that read data (for example, SELECT), but not statements that write data. MODIFIES SQL DATA: the routine contains statements that may write data (for example, INSERT or DELETE). The SQL SECURITY characteristic can be used to specify whether the routine should be executed using the permissions of the user who creates the routine or the user who invokes it.

10 Alter or Drop Routines ALTER {PROCEDURE | FUNCTION} sp_name [characteristic...] characteristic: { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } | SQL SECURITY { DEFINER | INVOKER } | COMMENT 'string' This statement can be used to change the characteristics of a stored procedure or function. DROP {PROCEDURE | FUNCTION} [IF EXISTS] sp_name This statement is used to drop a stored procedure or function.

11 Call Procedures or Functions CALL sp_name([parameter[,...]]) CALL sp_name[()] The CALL statement invokes a procedure that was defined previously with CREATE PROCEDURE. CALL can pass back values to its caller using parameters that are declared as OUT or INOUT parameters. It also “returns” the number of rows affected, which a client program can obtain at the SQL level by calling the ROW_COUNT() function and from other programming language by calling the mysql_affected_rows() API function.

12 Procedure Call Example CREATE PROCEDURE p (OUT ver_param VARCHAR(25), INOUT incr_param INT) BEGIN # Set value of OUT parameter SELECT VERSION() INTO ver_param; # Increment value of INOUT parameter SET incr_param = incr_param + 1; END; mysql> = 10; mysql> | | log | 11 |

13 BEGIN... END [begin_label:] BEGIN [statement_list] END [end_label] BEGIN... END syntax is used for writing compound statements, which can appear within stored routines and triggers. statement_list represents a list of one or more statements. Each statement within statement_list must be terminated by a semicolon (;) statement delimiter. Use of multiple statements requires that a client is able to send statement strings containing the ; statement delimiter. This is handled in the mysql command-line client by using the delimiter command to change the delimiter from ; to other symbols (e.g. //).

14 Declare variables in routines DECLARE var_name[,...] type [DEFAULT value] This statement is used to declare local variables. To provide a default value for the variable, include a DEFAULT clause. The value can be specified as an expression; it need not be a constant. If the DEFAULT clause is missing, the initial value is NULL. Local variables are treated like routine parameters with respect to data type and overflow checking. The scope of a local variable is within the BEGIN... END block where it is declared. The variable can be referred to in blocks nested within the declaring block, except those blocks that declare a variable with the same name.

15 Assign values to variables SET var_name = expr [, var_name = expr]... SELECT col_name[,...] INTO var_name[,...] table_expr The SET statement in stored routines is an extended version of the general SET statement. Referenced variables may be ones declared inside a routine, or global system variables. This SELECT syntax stores selected columns directly into variables. Therefore, only a single row may be retrieved. SELECT id,data INTO x,y FROM test.t1 LIMIT 1; Note: SQL variable names should not be the same as column names. If an SQL statement, such as a SELECT... INTO statement, contains a reference to a column and a declared local variable with the same name, MySQL currently interprets the reference as the name of a variable.

16 Flow Control - IF IF search_condition THEN statement_list [ELSEIF search_condition THEN statement_list]... [ELSE statement_list] END IF IF implements a basic conditional construct. If the search_condition evaluates to true, the corresponding SQL statement list is executed. If no search_condition matches, the statement list in the ELSE clause is executed. Each statement_list consists of one or more statements

17 Flow Control - CASE CASE case_value WHEN when_value THEN statement_list [WHEN when_value THEN statement_list]... [ELSE statement_list] END CASE CASE WHEN search_condition THEN statement_list [WHEN search_condition THEN statement_list]... [ELSE statement_list] END CASE The CASE statement for stored routines implements a complex conditional construct. If a search_condition evaluates to true, the corresponding SQL statement list is executed. If no search condition matches, the statement list in the ELSE clause is executed. Each statement_list consists of one or more statements.

18 Flow Control - LOOP [begin_label:] LOOP statement_list END LOOP [end_label] LOOP implements a simple loop construct, enabling repeated execution of the statement list, which consists of one or more statements. The statements within the loop are repeated until the loop is exited; usually this is accomplished with a LEAVE statement. A LOOP statement can be labeled. end_label cannot be given unless begin_label also is present. If both are present, they must be the same.

19 Flow Control - REPEAT [begin_label:] REPEAT statement_list UNTIL search_condition END REPEAT [end_label] The statement list within a REPEAT statement is repeated until the search_condition is true. REPEAT always enters the loop at least once. statement_list consists of one or more statements. A REPEAT statement can be labeled. end_label cannot be given unless begin_label also is present. If both are present, they must be the same.

20 Flow Control - WHILE [begin_label:] WHILE search_condition DO statement_list END WHILE [end_label] The statement list within a WHILE statement is repeated as long as the search_condition is true. statement_list consists of one or more statements. A WHILE statement can be labeled. end_label cannot be given unless begin_label also is present. If both are present, they must be the same.

21 Flow Control – LEAVE or ITERATE LEAVE label This statement is used to exit any labeled flow control construct. It can be used within BEGIN... END or loop constructs (LOOP, REPEAT, WHILE) ITERATE label ITERATE can appear only within LOOP, REPEAT, and WHILE statements. ITERATE means “do the loop again.”

22 Conditions DECLARE condition_name CONDITION FOR condition_value condition_value: SQLSTATE [VALUE] sqlstate_value | mysql_error_code This statement specifies conditions that need specific handling. It associates a name with a specified error condition. The name can subsequently be used in a DECLARE HANDLER statement. A condition_value can be an SQLSTATE value or a MySQL error code.

23 Handlers DECLARE handler_type HANDLER FOR condition_value[,...] statement handler_type: CONTINUE | EXIT | UNDO condition_value: SQLSTATE [VALUE] sqlstate_value | condition_name | SQLWARNING | NOT FOUND | SQLEXCEPTION | mysql_error_code The DECLARE... HANDLER statement specifies handlers that each may deal with one or more conditions. If one of these conditions occurs, the specified statement is executed.

24 Handler Types For a CONTINUE handler, execution of the current routine continues after execution of the handler statement. For an EXIT handler, execution terminates for the BEGIN... END compound statement in which the handler is declared. (This is true even if the condition occurs in an inner block.) The UNDO handler type statement is not yet supported. If a condition occurs for which no handler has been declared, the default action is EXIT.

25 References An Introduction to Database Systems, Eighth Edition, C. J. Date, Addison Wesley, 2004, ISBN: Database Management Systems, Third Edition, Raghu Ramakrishnan and Johannes Gehrke, McGraw-Hill, 2002, ISBN: