An Introduction to Stored Procedures in MySQL 5 by Federico Leven6 Apr 2011

Similar documents
Instructor: Craig Duckett. Lecture 14: Tuesday, May 15 th, 2018 Stored Procedures (SQL Server) and MySQL

Lesson 3 Transcript: Part 1 of 2 - Tools & Scripting

Lab 7 Macros, Modules, Data Access Pages and Internet Summary Macros: How to Create and Run Modules vs. Macros 1. Jumping to Internet

The Stack, Free Store, and Global Namespace

MySQL Stored Procedures

STORED PROCEDURE AND TRIGGERS

SQL Data Definition Language: Create and Change the Database Ray Lockwood

Stored Procedure. Stored procedures or functions. CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Create Stored Routines

Programming the Database

Introduction to Databases and SQL

Manual Trigger Sql Server Example Update Column Value

Stored procedures - what is it?

Sql Server 'create Schema' Must Be The First Statement In A Query Batch

COP 3718 Intermediate Database Systems. Chapter 13 Stored Procedures

Manual Trigger Sql Server Update Column Example

Stored Procedures and Functions

Lesson 3 Transcript: Part 2 of 2 Tools & Scripting

Manual Triggers Sql Server 2008 Examples

Manual Trigger Sql Server Update Column Changed

T-sql Check If Index Exists Information_schema

Meet MariaDB Vicențiu Ciorbaru Software MariaDB Foundation * * 2017 MariaDB Foundation

MySQL for Developers Ed 3

Class #7 Guidebook Page Expansion. By Ryan Stevenson

Mysql Tutorial Show Table Like Name Not >>>CLICK HERE<<<

Introduction to Computer Science and Business

PHP for PL/SQL Developers. Lewis Cunningham JP Morgan Chase

SQL STORED ROUTINES. CS121: Relational Databases Fall 2017 Lecture 9

Mastering phpmyadmiri 3.4 for

The Crypt Keeper Cemetery Software Online Version Tutorials To print this information, right-click on the contents and choose the 'Print' option.

MySQL for Developers Ed 3

SQL User Defined Code. Kathleen Durant CS 3200

SQL - Tables. SQL - Create a SQL Table. SQL Create Table Query:

Manual Trigger Sql Server 2008 Update Inserted Rows

Homework Assignment. 1. Stored Procedures (SPs)

Get Table Schema In Sql Server 2008 To Add Column If Not Exists >>>CLICK HERE<<<

Compare Two Identical Tables Data In Different Oracle Databases

Lesson B Objectives IF/THEN. Chapter 4B: More Advanced PL/SQL Programming

Oracle Database: Introduction to SQL/PLSQL Accelerated

Hello everyone! Page 1. Your folder should look like this. To start with Run your XAMPP app and start your Apache and MySQL.

MySQL: an application

DATABASE DESIGN - 1DL400

SQL Stored Programs. You Can Not Do Everything in SQL SQL/PSM Cursors Recursion Triggers. Niklas Fors Stored Programs 1 / 21

While you can always enter data directly into database tables, you might find it easier to use

! Emacs Howto Tutorial!

Today Learning outcomes LO2

Hello, and welcome to another episode of. Getting the Most Out of IBM U2. This is Kenny Brunel, and

Instructor: Craig Duckett. Lecture 02: Thursday, March 29 th, 2018 SQL Basics and SELECT, FROM, WHERE

ADVANTAGES. Via PL/SQL, all sorts of calculations can be done quickly and efficiently without use of Oracle engine.

Lecture 7 Stored procedure

Database Technology. Topic 6: Triggers and Stored Procedures

IBM DB2 9.7 SQL Procedure Developer.

Manual Trigger Sql Server 2008 Examples Insert Update

WINDOWS POWERSHELL 3.0 FIRST STEPS BY ED WILSON DOWNLOAD EBOOK : WINDOWS POWERSHELL 3.0 FIRST STEPS BY ED WILSON PDF

BEGINNER PHP Table of Contents

Introduction to SQL/PLSQL Accelerated Ed 2

Refactoring Without Ropes

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language

Manual Trigger Sql Server 2008 Update Inserted Or Deleted

THE PRAGMATIC INTRO TO REACT. Clayton Anderson thebhwgroup.com WEB AND MOBILE APP DEVELOPMENT AUSTIN, TX

1Z0-144 Q&As Oracle Database 11g: Program with PL/ SQL

What s New in MariaDB Server 10.3

In This Issue. The Enhanced Editor in QMF 11.2: Highlights. 1st Quarter 2016 Edition

Arduino IDE Friday, 26 October 2018

PHP Reference. To access MySQL manually, run the following command on the machine, called Sources, where MySQL and PhP have been installed:

Java Concepts: Compatible With Java 5, 6 And 7 By Cay S. Horstmann

d2vbaref.doc Page 1 of 22 05/11/02 14:21

It can be confusing when you type something like the expressions below and get an error message. a range variable definition a vector of sine values

Manual Trigger Sql Server 2008 Inserted Table Examples Insert

COM1004 Web and Internet Technology

Azon Master Class. By Ryan Stevenson Guidebook #9 Amazon Advertising

Oral Questions and Answers (DBMS LAB) Questions & Answers- DBMS

C Exam Questions Demo IBM. Exam Questions C

EE221 Databases Practicals Manual

Here's how you declare a function that returns a pointer to a character:

Sql Server 2008 Query Table Schema Management Studio Create

Get Table Schema In Sql Server 2005 Modify. Column Size >>>CLICK HERE<<<

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Slide 1 CS 170 Java Programming 1 Testing Karel

Tutorial on SQL Injection

CSC 326H1F, Fall Programming Languages. What languages do you know? Instructor: Ali Juma. A survey of counted loops: FORTRAN

WKA Studio for Beginners


What is SQL? Toolkit for this guide. Learning SQL Using phpmyadmin

Java4340r: Review. R.G. (Dick) Baldwin. 1 Table of Contents. 2 Preface

Clickteam Fusion 2.5 Creating a Debug System - Guide

DB2 for z/os Stored Procedure support in Data Server Manager

MITOCW watch?v=kz7jjltq9r4

Stored Procedures in MYSQL

SEER AKADEMI LINUX PROGRAMMING AND SCRIPTINGPERL 7

Actual4Test. Actual4test - actual test exam dumps-pass for IT exams

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Mysql Information Schema Update Time Null >>>CLICK HERE<<< doctrine:schema:update --dump-sql ALTER TABLE categorie

One Schema In Sql Server 2005 Management >>>CLICK HERE<<<

CircuitPython 101: Working with Lists, Iterators and Generators

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

Tutorials Php Y Jquery Mysql Database Without Refreshing Code

SQL*Loader Concepts. SQL*Loader Features

Notice on Access to Advanced Lists...2 Database Overview...2 Example: Real-life concept of a database... 2

Database Programming with PL/SQL

Transcription:

An Introduction to Stored Procedures in MySQL 5 by Federico Leven6 Apr 21 MySQL 5 introduced a plethora of new features - stored procedures being one of the most significant. In this tutorial, we will focus on what they are, and how they can make your life easier. If you work with MySQL a lot, you may want to check out the range of MySQL code scripts and plugins on Envato Market. Introduction A stored routine is a set of SQL statements that can be stored in the server. A stored procedure is a method to encapsulate repetitive tasks. They allow for variable declarations, flow control and other useful programming techniques. The academic position on this is quite clear and supports the extensive use of stored procedures. On the other hand, when you consider the opinions of those who work with them day in, day out, you'll notice that reactions vary from complete, unwavering support to utter hate. Keep these in mind. Pros Share logic with other applications. Stored procedures encapsulate functionality; this ensures that data access and manipulation are coherent between different applications. Isolate users from data tables. This gives you the ability to grant access to the stored procedures that manipulate the data but not directly to the tables.

Provide a security mechanism. Considering the prior item, if you can only access the data using the stored procedures defined, no one else can execute a DELETE SQL statement and erase your data. To improve performance because it reduces network traffic. With a stored procedure, multiple calls can be melded into one. Cons Increased load on the database server -- most of the work is done on the server side, and less on the client side. There's a decent learning curve. You'll need to learn the syntax of MySQL statements in order to write stored procedures. You are repeating the logic of your application in two different places: your server code and the stored procedures code, making things a bit more difficult to maintain. Migrating to a different database management system (DB2, SQL Server, etc) may potentially be more difficult. The tool that I am working with in this tutorial, MySQL Query Browser, is pretty standard for database interactions. The MySQL command line tool is another excellent choice. I make note of this because the popular phpmyadmin doesn't support stored procedure execution. Additionally, I'll be using very rudimentary table structures, strictly to ease the explanation. I'm showing off stored procedures, and they're complex enough without worrying about big tables. Step 1 - Picking a Delimiter The delimiter is the character or string of characters that you'll use to tell the mysql client that you've finished typing in an SQL statement. For ages, the delimiter has always been a semicolon. That, however, causes problems,

because, in a stored procedure, one can have many statements, and each must end with a semicolon. In this tutorial I will use // Step 2 - How to Work with a Stored Procedure Creating a Stored Procedure CREATE PROCEDURE `p2` () LANGUAGE SQL DETERMINISTIC SQL SECURITY DEFINER COMMENT 'A procedure' SELECT 'Hello World!'; END// The first part of the statement creates the procedure. The next clauses defines the optional characteristics of the procedure. Then you have the name and finally the body or routine code. Stored procedure names are case insensitive, and you cannot create procedures with the same name. Inside a procedure body, you can't put databasemanipulation statements. The four characteristics of a procedure are: Language : For portability purposes; the default value is SQL. Deterministic : If the procedure always returns the same results, given the same input. This is for replication and logging purposes. The default value is NOT DETERMINISTIC. SQL Security : At call time, check privileges of the user. INVOKER is the user who calls the procedure. DEFINER is the creator of the procedure. The default value is DEFINER.

Comment : For documentation purposes; the default value is "" Calling a Stored Procedure To call a procedure, you only need to enter the word CALL, followed by the name of the procedure, and then the parentheses, including all the parameters between them (variables or values). Parentheses are compulsory. CALL stored_procedure_name (param1, param2,...) CALL procedure1(, 'string parameter', @parameter_var); Modify a Stored Procedure MySQL provides an ALTER PROCEDURE statement to modify a routine, but only allows for the ability to change certain characteristics. If you need to alter the body or the parameters, you must drop and recreate the procedure. Delete a Stored Procedure 1 DROP PROCEDURE IF EXISTS p2; This is a simple command. The IF EXISTS clause prevents an error in case the procedure does not exist. Step 3 - Parameters Let's examine how you can define parameters within a stored procedure. CREATE PROCEDURE proc1 () : Parameter list is empty CREATE PROCEDURE proc1 (IN varname DATA-TYPE) : One input parameter. The word IN is optional because parameters are IN (input) by default. CREATE PROCEDURE proc1 (OUT varname DATA-TYPE) : One output parameter.

CREATE PROCEDURE proc1 (INOUT varname DATA-TYPE) : One parameter which is both input and output. Of course, you can define multiple parameters defined with different types. IN example 1 2 3 4 5 6 CREATE PROCEDURE `proc_in` (IN var1 INT) SELECT var1 + 2 AS result; END// OUT example 1 2 3 4 5 6 CREATE PROCEDURE `proc_out` (OUT var1 VARCHAR(0)) SET var1 = 'This is a test'; INOUT example 1 2 3 4 5 6 CREATE PROCEDURE `proc_inout` (OUT var1 INT) SET var1 = var1 * 2; Step 4 - Variables The following step will teach you how to define variables, and store values inside a procedure. You must declare them explicitly at the start of the /END block, along with their data types. Once you've declared a variable, you can use it anywhere that you could use a session variable, or literal, or column name.

Declare a variable using the following syntax: DECLARE varname DATA-TYPE DEFAULT defaultvalue; Let's declare a few variables: 1 2 3 4 5 6 7 DECLARE a, b INT DEFAULT 5; DECLARE str VARCHAR(50); DECLARE today TIMESTAMP DEFAULT CURRENT_DATE; DECLARE v1, v2, v3 TINYINT; Working with variables Once the variables have been declared, you can assign them values using the SET or SELECT command: CREATE PROCEDURE `var_proc` (IN paramstr VARCHAR(20)) DECLARE a, b INT DEFAULT 5; DECLARE str VARCHAR(50); DECLARE today TIMESTAMP DEFAULT CURRENT_DATE; DECLARE v1, v2, v3 TINYINT; INSERT INTO table1 VALUES (a); SET str = 'I am a string'; SELECT CONCAT(str,paramstr), today FROM table2 WHERE b >=5; Step 5 - Flow Control Structures MySQL supports the IF, CASE, ITERATE, LEAVE LOOP, WHILE and REPEAT constructs for flow control within stored programs. We're going to review how to use IF, CASE and WHILE specifically, since they happen to be the most commonly used statements in routines.

IF statement With the IF statement, we can handle tasks which involves conditions: 14 15 16 17 CREATE PROCEDURE `proc_if` (IN param1 INT) DECLARE variable1 INT; SET variable1 = param1 + 1; IF variable1 = 0 THEN SELECT variable1; END IF; IF param1 = 0 THEN SELECT 'Parameter value = 0'; ELSE SELECT 'Parameter value <> 0'; END IF; CASE statement The CASE statement is another way to check conditions and take the appropriate path. It's an excellent way to replace multiple IF statements. The statement can be written in two different ways, providing great flexibility to handle multiple conditions. 14 15 16 CREATE PROCEDURE `proc_case` (IN param1 INT) DECLARE variable1 INT; SET variable1 = param1 + 1; CASE variable1 WHEN 0 THEN INSERT INTO table1 VALUES (param1); WHEN 1 THEN INSERT INTO table1 VALUES (variable1); ELSE INSERT INTO table1 VALUES (99); END CASE;

17 or: 14 15 16 17 CREATE PROCEDURE `proc_case` (IN param1 INT) DECLARE variable1 INT; SET variable1 = param1 + 1; CASE WHEN variable1 = 0 THEN INSERT INTO table1 VALUES (param1); WHEN variable1 = 1 THEN INSERT INTO table1 VALUES (variable1); ELSE INSERT INTO table1 VALUES (99); END CASE; WHILE statement There are technically three standard loops: WHILE loops, LOOP loops, and REPEAT loops. You also have the option of creating a loop using the Darth Vader of programming techniques: the GOTO statement. Check out this example of a loop in action: CREATE PROCEDURE `proc_while` (IN param1 INT) DECLARE variable1, variable2 INT; SET variable1 = 0; WHILE variable1 < param1 DO INSERT INTO table1 VALUES (param1); SELECT COUNT(*) INTO variable2 FROM table1; SET variable1 = variable1 + 1; END WHILE; Advertisement

Step 6 - Cursors Cursor is used to iterate through a set of rows returned by a query and process each row. MySQL supports cursor in stored procedures. Here's a summary of the essential syntax to create and use a cursor. DECLARE cursor-name CURSOR FOR SELECT...; the cursor with a SELECT statement */ DECLARE CONTINUE HANDLER FOR NOT FOUND when no more records found*/ OPEN cursor-name; use*/ FETCH cursor-name INTO variable [, variable]; with the current column values*/ CLOSE cursor-name; /*Declare and populate /*Specify what to do /*Open cursor for /*Assign variables /*Close cursor after use*/ In this example, we'll perform some simple operations using a cursor: 14 15 16 17 18 19 CREATE PROCEDURE `proc_cursor` (OUT param1 INT) DECLARE a, b, c INT; DECLARE cur1 CURSOR FOR SELECT col1 FROM table1; DECLARE CONTINUE HANDLER FOR NOT FOUND SET b = 1; OPEN cur1; SET b = 0; SET c = 0; WHILE b = 0 DO FETCH cur1 INTO a; IF b = 0 THEN SET c = c + a; END IF; END WHILE; CLOSE cur1; SET param1 = c;

20 21 22 23 Cursor has three important properties that you need to be familiar with in order to avoid unexpected results: Asensitive : Once open, the cursor will not reflect changes in its source tables. In fact, MySQL does not guarantee the cursor will be updated, so you can't rely on it. Read Only : Cursors are not updatable. Not Scrollable : Cursors can be traversed only in one direction, forward, and you can't skip records from fetching. Conclusion In this lesson, we covered the fundamentals of stored procedures and some specific properties pertaining to them. Of course, you should continue your studies in areas like security, SQL statements, and performance before you can master MySQL routines. You have to evaluate the advantages that stored procedures can potentially bring to your applications, and then make a reasonable implementation that fits your requirements. I generally use procedures; their benefits in terms of security, code maintenance and software design make them worthy of use, in my opinion. Additionally, remember that procedures in MySQL are still a work in progress. You should fully expect improvements, in terms of functionality and performance in the future. Please don't hesitate to comment and share your ideas and opinions. And have a look at the MySQL code scripts and plugins on Envato Market to see if you find anything to help you there.