30
Stored Procedures

Procedures and triggers in SQL

Embed Size (px)

Citation preview

Stored Procedures

Outlines of Session

· Why Procedures in MySQL/MSSQL

· Advantages

· Syntax

· LIVE creation & Execution of procedures

· DB connection with MSSQL

· Procedures VS Functions

· Triggers : Usage & implementation

· LIVE creation & Execution of Database triggers

Stored Procedures in MySQL

A stored procedure contains a

sequence of SQL commands stored in

the database catalog so that it can be

invoked later by a program

Procedures in MySQL - Why?

Why go to the trouble of extracting logic

from your application, putting it into a

different format, and placing it on the

database server?

Procedures in MySQL - Advantages

Advantages:

● FASTER in general than using app program

● Improve the security of server

● Not subject to SQL injection attacks.

● Encapsulation of business logic

● Portable

● Server Overhead

● Avoidance of network traffic

● Stored procedures are declared using the following syntax:

Create Procedure <proc-name>

(param_spec1, param_spec2, …, param_specn )

begin

-- execution code

end;

where each param_spec is of the form:

[in | out | inout] <param_name> <param_type>

– in mode: allows you to pass values into the procedure,

– out mode: allows you to pass value back from procedure to the calling

program

Procedures in MySQL - Declaration

Procedures in MySQL - Example 1

mysql> delimiter //

mysql> CREATE PROCEDURE dorepeat(p1 INT)

-> BEGIN

-> SET @x = 0;

-> REPEAT SET @x = @x + 1;

-> UNTIL @x > p1;

-> END REPEAT;

-> END

-> //

Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;

mysql> CALL dorepeat(1000);

Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @x;

+------+

| @x |

+------+

| 1001 |

+------+

1 row in set (0.00 sec)

SET @x = 0;

REPEAT SET @x = 0 + 1;

UNTIL 1 > 1000

END REPEAT;

DELIMITER $$

CREATE PROCEDURE CountPartByType

(IN PartType VARCHAR(2),

OUT total INTEGER)

BEGIN

SELECT count(Part_Num) INTO total

FROM PART

WHERE Class = PartType;

END$$

DELIMITER ;

Call CountPartByType ('HW',@total); //in command line

SELECT @total;

$result = mysql_query('CALL CountPartByType('HW',@total)'); //in php

Procedures in MySQL - Example 2

Connecting MS SQL - In Cake

Path : /app/Config/database.php

The name of a supported datasource; valid options are as follows:

* Database/Mysql - MySQL 4 & 5,

* Database/Sqlite - SQLite (PHP5 only),

* Database/Postgres - PostgreSQL 7 and higher,

* Database/Sqlserver - Microsoft SQL Server 2005 and higher

Eg.

public $default = array(

'datasource' => 'Database/Sqlserver',

'persistent' => false,

'host' => 'localhost',

'login' => '**********',

'password' => '**********',

'database' => '**********',

'prefix' => '',

'encoding' => 'utf8',

);

Functions V/S Procedures MySQL

could be used in SELECT statements,

provided they don’t do any data

manipulation.

cannot be included in SELECT statements.

must return a value (using the RETURN

keyword), but for stored procedures this is

not compulsory.

can use RETURN keyword but without any

value being passed.A stored procedure can

return multiple values using the OUT

parameter or return no value at all.

A function is a subprogram written to

perform certain computations

A scalar function returns only a single value

(or NULL), whereas a table function returns

a (relational) table comprising zero or more

rows, each row with one or more columns.

Functions Procedures

Its not a DB object. A stored procedure is a database object.

A stored procedure saves the query

compilation time.

Example

● Suppose we want to keep track of the total salaries of employees

working for each department

We need to write a procedure

to update the salaries in

the deptsal table

Example

Step 1: Change the delimiter (i.e., terminating character) of

SQL statement from semicolon (;) to something else (e.g., //)

So that you can distinguish between the semicolon of the SQL

statements in the procedure and the terminating character of

the procedure definition

Example

Step 2:

1. Define a procedure called updateSalary which takes as

input a department number.

2. The body of the procedure is an SQL command to update

the totalsalary column of the deptsal table.

3. Terminate the procedure definition using the delimiter you

had defined in step 1 (//)

Example

Step 3: Change the delimiter back to semicolon (;)

Example

Step 4: Call the procedure to update the totalsalary for each

department

Example

Step 5: Show the updated total salary in the deptsal table

Stored Procedures in MySQL

● Use show procedure status to display the list of stored

procedures you have created

● Use drop procedure to remove a stored procedure

Stored Procedures in MySQL

● You can declare variables in stored procedures

● You can use flow control statements (conditional IF-

THEN-ELSE or loops such as WHILE and REPEAT)

Another Example

● Create a procedure to give a raise to all employees

Another Example

Another Example

SQL Triggers

● To monitor a database and take a corrective action when a condition

occurs

– Examples:

◆ Charge $10 overdraft fee if the balance of an account after a withdrawal

transaction is less than $500

◆ Limit the salary increase of an employee to no more than 5% raise

CREATE TRIGGER trigger-name

trigger-time trigger-event

ON table-name

FOR EACH ROW

trigger-action;

– trigger-time ∈ {BEFORE, AFTER}

– trigger-event ∈ {INSERT,DELETE,UPDATE}

SQL Triggers: An Example

● We want to create a trigger to update the total salary of a

department when a new employee is hired

SQL Triggers: An Example

● Create a trigger to update the total salary of a department

when a new employee is hired:

● The keyword “new” refers to the new row inserted

SQL Triggers: An Example

totalsalary increases by 90K

totalsalary did not change

SQL Triggers: An Example

● A trigger to update the total salary of a department when an employee tuple is modified(insert/delete):

SQL Triggers: An Example

SQL Triggers: An Example

● A trigger to update the total salary of a department when an employee tuple is deleted:

SQL Triggers: An Example

SQL Triggers

● To list all the triggers you have created:

mysql> show triggers;