Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL...

71
Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1

Transcript of Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL...

Page 1: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

1

Instructor: Craig Duckett

Lecture 14: Tuesday, May 26, 2015Stored Procedures (SQL Server) and MySQL

Page 2: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

2

We will be looking at Microsoft SQL Server, Azure, virtual server, and Visual Studio until the end of the quarter.

On Thursday: I will be introducing Visual Studio 2013 Community Edition and using it to create stored procedure functions for use with SQL Server

• Final Exam is LECTURE 20, Tuesday, June 16th

• Assignment 3 is due LECTURE 19, Thursday, June 11th, in StudentTracker by MIDNIGHT

Page 3: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

3

Tuesday/Thursday (LECTURE 14)• Database Design for Mere Mortals: Chapters 10, 11

Page 4: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

4

• Stored Procedures (SQL Server)• Stored Procedure Slides (MySQL, FOR REFERENCE ONLY)

Page 5: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

5

What Are Stored Procedures ?

Page 6: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures

Up until now, all of our data retrieval has been accomplished with a single statement. Even the use of subqueries was accomplished by combining two SELECTs into a single statement. We’re now going to discuss a new scenario in which multiple statements can be saved into a single object known as a stored procedure.

A Stored Procedure is a set of SQL statements, compiled and stored as a single database object for repeated use.

• It is used to get information from the database or change data in the database• It is used by application programs (along with views)• It can use zero or more parameters• It is run using an EXECUTE statement (in MS SQL SERVER) or CALL (in MySQL) with the procedure

name and any parameter values• It is built using a CREATE PROCEDURE statement.

Page 7: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures

In broad terms, there are two general reasons why you might want to use stored procedures:

■ To save multiple SQL statements in a single procedure ■ To use parameters in conjunction with your SQL statements

Stored procedures can, in fact, consist of a single SQL statement and contain no parameters.

But the real value of stored procedures becomes evident when they contain multiple statements or parameters.

This is something that relates directly to the issue of how to best retrieve data from a database.

Page 8: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored ProceduresBasically, the ability to store multiple statements in a procedure means that you can create complex logic and execute it all at once as a single transaction.

For example, you might have a business requirement to take an incoming order from a customer and quickly evaluate it before accepting it from the customer.

This procedure might involve:

• checking to make sure that the items are in stock• verifying that the customer has a good credit rating• getting an initial estimate as to when it can be shipped

This situation would require multiple SQL statements with some added logic to determine what kind of message to return if all were not well with the order. All of that logic could be placed into a single stored procedure, which would enhance the modularity of the system.

With everything in one procedure, that logic could be executed from any calling program, and it would always return the same result.

Page 9: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures

Why Use Stored Procedures?

One of the most beneficial reasons to use stored procedures is the added layer of security that can be placed on the database from the calling application.

If the user account created for the application or web site is configured with permissions only then the underlying tables cannot be accessed directly by the user account. This helps prevent hacking directly into the database tables.

The risk of a hacker using the user account to run a stored procedure that has been written by you is far safer than having the user account have full insert, update and delete authority on the tables directly.

Page 10: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored ProceduresBenefits of Stored Procedures

• Modular Programming – You can write a stored procedure once, then call it from multiple places in your application.

• Performance - Stored procedures provide faster code execution and reduce network traffic. • Faster execution: Stored procedures are parsed and optimized as soon as they are created and the stored

procedure is stored in memory. This means that it will execute a lot faster than sending many lines of SQL code from your application to the SQL Server. Doing that requires SQL Server to compile and optimze your SQL code every time it runs.

• Reduced network traffic: If you send many lines of SQL code over the network to your SQL Server, this will impact on network performance. This is especially true if you have hundreds of lines of SQL code and/or you have lots of activity on your application. Running the code on the SQL Server (as a stored procedure) eliminates the need to send this code over the network. The only network traffic will be the parameters supplied and the results of any query.

• Security - Users can execute a stored procedure without needing to execute any of the statements directly. Therefore, a stored procedure can provide advanced database functionality for users who wouldn't normally have access to these tasks, but this functionality is made available in a tightly controlled way.

Page 11: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored ProceduresDisadvantages of Stored Procedures

• 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 not only the syntax of SQL statements in order to write stored procedures, but the particular "dialect" of the DBMS managing them (e.g., SSQL Server T-SQL vs. MySQL vs Oracle vs DBs)

• 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 (MySQL, SQL Server, Oracle, DB2, etc) may potentially be more difficult.

Page 12: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

12

Stored Procedures (SQL Server and T-SQL)

Summary Overview

A stored procedure is nothing more than prepared SQL code that you save so you can reuse the code over and over again. So if you think about a query that you write over and over again, instead of having to write that query each time you would save it as a stored procedure and then just call the stored procedure to execute the SQL code that you saved as part of the stored procedure.

In addition to running the same SQL code over and over again you also have the ability to pass parameters to the stored procedure, so depending on what the need is the stored procedure can act accordingly based on the parameter values that were passed.

http://www.codeproject.com/Articles/38682/Overview-of-SQL-Server-Stored-Procedure

http://www.mssqltips.com/sqlservertip/1495/getting-started-with-sql-server-stored-procedures/

Page 13: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL

Different Options for Creating SQL Server Stored Procedures

There are various options that can be used to create stored procedures. In these next few topics we will discuss creating a simple stored procedure to more advanced options that can be used when creating stored procedures.

• Creating a simple stored procedure• Using input parameters• Using output parameters• Using Try Catch (REFERENCE LINK ONLY)

Page 14: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

14

SelectCustomers Stored Procedure

Page 15: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL

Creating a Simple Stored Procedure

As mentioned in the overview a stored procedure is nothing more than stored SQL code that you would like to use over and over again. In this example we will look at creating a simple stored procedure.

Explanation

Before you create a stored procedure you need to know what your end result is, whether you are selecting data, inserting data, etc..

In this simple example we will just select specific data from the Customer table that is stored in the Northwind database.

Page 16: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL

To create a simple stored procedures in Object Explorer

1. Expand the Northwind database in SQL Server > Object Explorer.

2. Expand the Programmability folder and right-click on Stored Procedures and select New Stored Procedure

Page 17: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL3. This will create a stored procedure template from the Template Explorer

Page 18: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL4. Replace the template CREATE PROCEDURE code with the following, then Execute:

CREATE PROCEDURE SelectCustomersAS SET NOCOUNT ON;SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax FROM Customers

SET NOCOUNT ON: Stops the message that shows the count of the number of rows affected by a Transact-SQL statement or stored procedure from being returned as part of the result set.

Page 19: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL5. The new SelectCustomers stored procedure is now part of the Stored Procedures folder (you may

have to right-click and select Refresh to have it show up)

Page 20: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL6. To run the SelectCustomers, right-click on it and select Execute Stored Procedure (then click Go on

the Execute Stored Procedure window)

7. You could have also just run a query using EXECUTE SelectCustomers (or EXEC SelectCustomers for short)

Page 21: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

21

InsertCustomers Stored Procedure

Page 22: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL

To create a stored procedures with parameters

1. Expand the Northwind database in SQL Server > Object Explorer.

2. Expand the Programmability folder and right-click on Stored Procedures and select New Stored Procedure

Page 23: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL3. This will create a stored procedure template from the Template Explorer

Page 24: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL4. Replace the template CREATE PROCEDURE code with the following InsertCustomers, then Execute:

CREATE PROCEDURE InsertCustomers( @CustomerID nchar(5), @CompanyName nvarchar(40), @ContactName nvarchar(30), @ContactTitle nvarchar(30), @Address nvarchar(60), @City nvarchar(15), @Region nvarchar(15), @PostalCode nvarchar(10), @Country nvarchar(15), @Phone nvarchar(24), @Fax nvarchar(24))AS SET NOCOUNT OFF;INSERT INTO Customers ([CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address], [City], [Region], [PostalCode], [Country], [Phone], [Fax]) VALUES (@CustomerID, @CompanyName, @ContactName, @ContactTitle, @Address, @City, @Region, @PostalCode, @Country, @Phone, @Fax);

Page 25: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

NOTE: The InsertCustomers stored procedure is added to the Northwind database. Notice that the procedure definition will change from CREATE PROCEDURE to ALTER PROCEDURE when you execute it.

Page 26: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL6. To run the InsertCustomers, right-click on it

and select Execute Stored Procedure (fill in the required data then click Go on the Execute Stored Procedure window)

Page 27: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL7. You could have also just run a query using EXECUTE InsertCustomers (or EXEC InsertCustomers for

short) as such:

EXEC InsertCustomers WIN, WinkusWare, 'Rex Winkus', CEO, '123 Main', Bothell, West, 98011, USA, 4255551234, Null

Page 28: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL8. Right-clicking and running a Select Top 1000

Rows on the Customers table will display the new customer row that was added:

Page 29: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

29

UpdateCustomers Stored Procedure

Page 30: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL

To create a stored procedures to alter parameters

1. Expand the Northwind database in SQL Server > Object Explorer.

2. Expand the Programmability folder and right-click on Stored Procedures and select New Stored Procedure

Page 31: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL3. This will create a stored procedure template from the Template Explorer

Page 32: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL4. Replace the template CREATE PROCEDURE code with the following UpdateCustomers, then Execute:

CREATE PROCEDURE UpdateCustomers( @CustomerID nchar(5), @CompanyName nvarchar(40), @ContactName nvarchar(30), @ContactTitle nvarchar(30), @Address nvarchar(60), @City nvarchar(15), @Region nvarchar(15), @PostalCode nvarchar(10), @Country nvarchar(15), @Phone nvarchar(24), @Fax nvarchar(24), @Original_CustomerID nchar(5))AS SET NOCOUNT OFF;UPDATE Customers SET [CustomerID] = @CustomerID, [CompanyName] = @CompanyName, [ContactName] = @ContactName, [ContactTitle] = @ContactTitle, [Address] = @Address, [City] = @City, [Region] = @Region, [PostalCode] = @PostalCode, [Country] = @Country, [Phone] = @Phone, [Fax] = @Fax WHERE (([CustomerID] = @Original_CustomerID));

SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax FROM Customers WHERE (CustomerID = @CustomerID)

Page 33: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.
Page 34: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL6. To run the UpdateCustomers, right-click on

it and select Execute Stored Procedure (fill in the required data then click Go on the Execute Stored Procedure window)

Page 35: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.
Page 36: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

6. Right-clicking and running a Select Top 1000 Rows on the Customers table will display the customer row that was altered:

Page 37: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

37

DeleteCustomers Stored Procedure

Page 38: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL

To create a stored procedures to delete Customer row

1. Expand the Northwind database in SQL Server > Object Explorer.

2. Expand the Programmability folder and right-click on Stored Procedures and select New Stored Procedure

Page 39: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL3. This will create a stored procedure template from the Template Explorer

Page 40: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures with SQL Server and T-SQL4. Replace the template CREATE PROCEDURE code with the following DeleteCustomers, then Execute:

CREATE PROCEDURE DeleteCustomers( @Original_CustomerID nchar(5))AS SET NOCOUNT OFF;DELETE FROM Customers WHERE (([CustomerID] = @Original_CustomerID))

Page 41: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.
Page 42: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.
Page 43: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.
Page 44: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

44

To DROP or DELETE a Stored Procedure

Page 45: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

DELETE or DROP a Stored Procedure with SQL Server

• Either right-click on the stored procedure and select Delete, or run a DROP script:

DROP PROCEDURE ProcedureName

Page 46: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

SQL Server Stored Procedure Links of Interests• MSSQLTips: • http://www.mssqltips.com/sqlservertip/1495/getting-started-with-sql-server-stored-procedures/• Code Project:

http://www.codeproject.com/Articles/38682/Overview-of-SQL-Server-Stored-Procedure • MSSQLtips:

http://www.mssqltips.com/sqlservertutorial/161/creating-a-simple-stored-procedure/ • MSSQLTips:

http://www.mssqltips.com/sqlservertutorial/162/how-to-create-a-sql-server-stored-procedure-with-parameters/ • MSSQLTips:

http://www.mssqltips.com/sqlservertutorial/163/returning-stored-procedure-parameter-values-to-a-calling-stored-procedure/ • MSSQLTips:

http://www.mssqltips.com/sqlservertutorial/164/using-try-catch-in-sql-server-stored-procedures/ • MSSQLTips:

http://www.mssqltips.com/sqlservertutorial/167/using-comments-in-a-sql-server-stored-procedure/ • MSSQLTips:

http://www.mssqltips.com/sqlservertutorial/169/naming-conventions-for-sql-server-stored-procedures/ • MSSQLTips:

http://www.mssqltips.com/sqlservertutorial/172/reducing-amount-of-network-data-for-sql-server-stored-procedures/ MSSQLTips: http://www.mssqltips.com/sqlservertutorial/173/deleting-a-sql-server-stored-procedure/

• MSSQLTips: http://www.mssqltips.com/sqlservertutorial/174/modifying-an-existing-sql-server-stored-procedure/

Page 47: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

47

Stored Procedures & Triggers (MySQL)

FOR REFERENCE ONLY

Page 48: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored ProceduresMySQL and Stored Procedures

MySQL is known as the most popular open source RDBMS which is widely used by both community and enterprise.

However during the first decade of its existence, it did not support stored procedures, triggers, events, etc.

Since MySQL version 5.0 (release in 2009) , those features have been added to MySQL database engine to make it become flexible and powerful.

What follows is a look at stored procedures and how they are created and called in MySQL (we will look at stored procedures in Microsoft SQL Server on another day, after we've had some time to first learn a few of its operating nuances).

http://mysqlstoredprocedure.com/

Page 49: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored ProceduresHow to View MySQL Stored Procedure in PhpMyAdmin?

1. In PhpMyAdmin, select the correct database on the left hand panel2. You can see all the database tables in the right hand panel3. Scroll down the right hand panel until the end, you will see Routines4. Click on Routines5. All the Stored Procedures will be displayed on screen

Page 50: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored ProceduresCreating a MySQL Stored Procedure in PhpMyAdmin

Developers may have some issues creating a stored procedure in phpMyAdmin, which seems has issues supporting (or rather, not supporting) stored procedures, but there is a simple fix.

First off, let's look at some attempted stored procedure code:

Pretty easy, right? But it causes this error:

Okay, so what's the simple fix? The next section about creating stored procedures in MySQL should make everything clear.

Page 51: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored ProceduresChanging the 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. What one can do is to change the delimiter to something else, something other than a semicolon.

In this brief overview I'll be using // (you can use anything you want, $$ for example)

Creating a Stored Procedure

Page 52: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures

Let’s examine the stored procedure in a greater detail:

The first command is DELIMITER //, which is not related to the stored procedure syntax. The DELIMITER statement changes the standard delimiter which is semicolon ( ; ) to another. In this case, the delimiter is changed from the semicolon ( ; ) to double-slashes //. Why do we have to change the delimiter? because we want to pass the stored procedure to the server as a whole instead of letting MySQL interpret each statement one at a time when we type. Following the END keyword, we use delimiter // to indicate the end of the stored procedure. The last command DELIMITER ; changes the delimiter back to the semicolon ( ; ).

The CREATE PROCEDURE statement is used to create a new stored procedure. You can specify the name of stored procedure after the CREATE PROCEDURE statement. In this case, the name of the stored procedure is GetAllProducts. Do not forget the parenthesis ( ) after the name of the store procedure or you will get an error message.

Everything inside a pair of keyword BEGIN and END is called stored procedure’s body. You can put the declarative SQL code inside the stored procedure’s body to handle business logic. In the store procedure we used simple SQL SELECT statement to query data from the products table

Page 53: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored ProceduresCalling 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 (required).

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

Drop (Delete) A Stored Procedure

This is a simple command. The IF EXISTS clause prevents an error in case the procedure does not exist.

Page 54: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Parameters (in a Stored Procedure)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 OUT Example

INOUT Example

Page 55: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Variables (Stored Procedures)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 BEGIN/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:

Let's look at a few variables:

Page 56: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Variables (Stored Procedures)Working with Variables

Once the variables have been declared, you can assign them values using the SET or SELECT command:

Page 57: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Flow Control StructuresMySQL 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

Page 58: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Flow Control StructuresCASE 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

Page 59: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Flow Control StructuresWHILE 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:

Page 60: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Cursors (Stored Procedures)"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.

A ‘cursor’ in MySQL is essentially just the result set that’s returned from a query. Using a cursor allows you to iterate, or step through, the results of a query and perform certain operations on each row that’s returned.

Think of them like holders for any data you might process in a loop

Page 61: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Parameter, Result Set, Return Value• A Parameter is a variable passed to a stored procedure. Parameters can be used• for either input or output.

• A Result Set is the set of data values returned by a SELECT statement

• A Return Value is an integer value returned by a stored procedure, often used to send an error message to the caller

Variables• You can store a value in a user-defined variable in one statement and then refer to it later in

another statement. This enables you to pass values from one statement to another. User-defined variables are session-specific. That is, a user variable defined by one client cannot be seen or used by other clients. All variables for a given client session are automatically freed when that client exits. User variables are written as @var_name

• One way to set a user-defined variable is by issuing a SET statement:

• SET @var_name = expr [, @var_name = expr] ...

• For SET, either = or := can be used as the assignment operator.

Page 62: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

FunctionsA Function is a SQL object used to evaluate an expression and return data

• Used to get information from the database. It can't change data.

• Used internally by other functions, stored procedures, or views

• Can use zero or more parameters

• Call the function by name with any parameter value(s) enclosed in parenthesis, separated by commas

• Built using a CREATE FUNCTION statement.

Page 63: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

TriggersBy definition, a trigger or database trigger is a stored program (much like a stored procedure) that is executed automatically to respond to a specific event associated with table e.g., insert, update or delete. In other words, a stored program has been triggered to fire off automatically in response to a specified event or series of events occurring within the database.

A SQL trigger is also known as a special type of stored procedure because it is not called directly by users like a stored procedure. The main difference between a trigger and a stored procedure is that a trigger is called automatically when a data modification event is made against a table while a stored procedure must be called explicitly.

It is important to understand SQL trigger’s advantages and disadvantages using SQL triggers. In the following sections, we will discuss about the advantages and disadvantages of using SQL triggers in more detail.

Advantages of using SQL Triggers

• SQL trigger provides an alternative way to check the integrity of data.• SQL trigger can catch errors in business logic in the database layer.• SQL trigger provides an alternative way to run scheduled tasks. • SQL trigger is very useful to audit the changes of data in a tables.

Disadvantages of using SQL Triggers

• SQL trigger only can provide an extended validation and it cannot replace all the validations. Some simple validations has to be done in the application layer.

• SQL trigger is invoked and executed invisibly from client-applications therefore it is difficult to figure out what happen in the database layer.

• SQL trigger may increase the overhead of the database server.

Page 64: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

TriggersMySQL Trigger Syntax

In order to create a trigger you use CREATE TRIGGER statement. The following illustrates the syntax of the CREATE TRIGGER statement

Let’s examine the syntax above in more detail.

• You put the trigger name after the CREATE TRIGGER statement. The trigger name should follow the naming convention [trigger time]_[table name]_[trigger event], for example before employees_update.

• Trigger activation time can be BEFORE or AFTER. You must specify the activation time when you define a trigger. You use BEFORE keyword if you want to process action prior to the change is made on the table and AFTER if you need to process action after change are made.

• Trigger event can be INSERT, UPDATE and DELETE. These events cause triggers to be invoked. A trigger only can be invoked by one event. To define a trigger that is invoked by multiple events, you have to define multiple triggers, one for each event.

• A trigger must be associated with a specific table. Without a table, trigger would not exist therefore you have to specify the table name after the ON keyword.

• The SQL code is placed between BEGIN and END keywords.• The OLD and NEW keywords help you develop trigger more efficient. The OLD keyword refers to the

existing record before you change the data and the NEW keyword refers to the new row after you change the data.

Page 65: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

TriggersMySQL Trigger Example

Let’s start creating a trigger in MySQL to audit the changes of the employees table. First, we have an employees table in our MySQL sample database as follows:

Second, we create a new table named employees_audit to keep the change of the employee records. This script creates the employee_audit table

Third, we create the BEFORE UPDATE trigger to be invoked before a change is made to the employee records.

Page 66: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

TriggersMySQL Trigger Example

If you take a look at the schema, you will see before_employee_update trigger under the employees table as follows:

To check if the trigger was invoked by the UPDATE statement, we can query the employees_audit table

Now it’s time to update an employee record to test if the trigger is really invoked.

The following is the output of the query:

As you see, our trigger was really invoked so that we have a new record in the employees_audit table

Page 67: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

67

Stored Procedures in MySQL Workbench

Page 68: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures (MySQL Workbench)It’s kind of tedious to write the store procedure in MySQL especially when the stored procedure is complex. Most of the GUI tool for MySQL allows you to create new stored procedures using an intuitive interface. For example, in MySQL Workbench, you can create a new stored procedure as follows:

Page 69: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures (MySQL Workbench)

Page 70: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures (MySQL Workbench)

Page 71: Instructor: Craig Duckett Lecture 14: Tuesday, May 26, 2015 Stored Procedures (SQL Server) and MySQL 1.

Stored Procedures (MySQL Workbench)

Calling a stored procedure: