Top Banner
Stored Procedures
30

Procedures and triggers in SQL

Jul 19, 2015

Download

Education

Vikash Sharma
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Procedures and triggers in SQL

Stored Procedures

Page 2: Procedures and triggers in SQL

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

Page 3: Procedures and triggers in SQL

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

Page 4: Procedures and triggers in SQL

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?

Page 5: Procedures and triggers in SQL

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

Page 6: Procedures and triggers in SQL

● 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

Page 7: Procedures and triggers in SQL

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;

Page 8: Procedures and triggers in SQL

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

Page 9: Procedures and triggers in SQL

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',

);

Page 10: Procedures and triggers in SQL

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.

Page 11: Procedures and triggers in SQL

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

Page 12: Procedures and triggers in SQL

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

Page 13: Procedures and triggers in SQL

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 (//)

Page 14: Procedures and triggers in SQL

Example

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

Page 15: Procedures and triggers in SQL

Example

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

department

Page 16: Procedures and triggers in SQL

Example

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

Page 17: Procedures and triggers in SQL

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

Page 18: Procedures and triggers in SQL

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)

Page 19: Procedures and triggers in SQL

Another Example

● Create a procedure to give a raise to all employees

Page 20: Procedures and triggers in SQL

Another Example

Page 21: Procedures and triggers in SQL

Another Example

Page 22: Procedures and triggers in SQL

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}

Page 23: Procedures and triggers in SQL

SQL Triggers: An Example

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

department when a new employee is hired

Page 24: Procedures and triggers in SQL

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

Page 25: Procedures and triggers in SQL

SQL Triggers: An Example

totalsalary increases by 90K

totalsalary did not change

Page 26: Procedures and triggers in SQL

SQL Triggers: An Example

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

Page 27: Procedures and triggers in SQL

SQL Triggers: An Example

Page 28: Procedures and triggers in SQL

SQL Triggers: An Example

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

Page 29: Procedures and triggers in SQL

SQL Triggers: An Example

Page 30: Procedures and triggers in SQL

SQL Triggers

● To list all the triggers you have created:

mysql> show triggers;