SlideShare a Scribd company logo
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
Procedures in MySQL - Declaration 
● 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 - 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;
Procedures in MySQL - Example 2 
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
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 
Functions Procedures 
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. 
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;

More Related Content

PPTX
Introduction to database & sql
PPTX
SQL(DDL & DML)
PPT
1 - Introduction to PL/SQL
PPTX
Chapter 1 introduction to sql server
PPTX
Er diagrams presentation
PPTX
Cohesion and coupling
PPTX
SQL - DML and DDL Commands
Introduction to database & sql
SQL(DDL & DML)
1 - Introduction to PL/SQL
Chapter 1 introduction to sql server
Er diagrams presentation
Cohesion and coupling
SQL - DML and DDL Commands

What's hot (20)

PPT
Data Structures- Part5 recursion
PPT
Data models
PPTX
5. stored procedure and functions
PDF
Lecture4 big data technology foundations
PPTX
Relational Data Model Introduction
PPTX
Dbms and rdbms ppt
PPTX
Triggers
PPT
1. Introduction to DBMS
ODP
Introduction to triggers
PPT
Files Vs DataBase
PPTX
Semaphore
PPTX
Deadlock ppt
PPTX
PPT
Advanced sql
ODP
Partitioning
PPT
File organization 1
PPTX
Basic sql Commands
PDF
ORACLE ARCHITECTURE
PPTX
Data Structures- Part5 recursion
Data models
5. stored procedure and functions
Lecture4 big data technology foundations
Relational Data Model Introduction
Dbms and rdbms ppt
Triggers
1. Introduction to DBMS
Introduction to triggers
Files Vs DataBase
Semaphore
Deadlock ppt
Advanced sql
Partitioning
File organization 1
Basic sql Commands
ORACLE ARCHITECTURE
Ad

Viewers also liked (20)

PPTX
Sub-queries,Groupby and having in SQL
PPTX
trigger dbms
PPTX
View, Store Procedure & Function and Trigger in MySQL - Thaipt
PPTX
RTF
Trigger and cursor program using sql
PPT
Trigger
PDF
Bai giang hqtcsdl
PPTX
Triggers
PPT
What's new in Apache Hive
PPTX
Sql tutorial
ODP
Ms sql-server
PDF
Sql db optimization
PPTX
MS SQL SERVER: Creating Views
PDF
Using grouping sets in sql server 2008 tech republic
PPTX
Consultas en MS SQL Server 2012
PPTX
Introduction to triggers
DOCX
Database Security
PPS
Sql xp 04
PPT
Sql tuning guideline
Sub-queries,Groupby and having in SQL
trigger dbms
View, Store Procedure & Function and Trigger in MySQL - Thaipt
Trigger and cursor program using sql
Trigger
Bai giang hqtcsdl
Triggers
What's new in Apache Hive
Sql tutorial
Ms sql-server
Sql db optimization
MS SQL SERVER: Creating Views
Using grouping sets in sql server 2008 tech republic
Consultas en MS SQL Server 2012
Introduction to triggers
Database Security
Sql xp 04
Sql tuning guideline
Ad

Similar to Procedures and triggers in SQL (20)

PPT
lecture13.ppt
DOC
Subqueries views stored procedures_triggers_transactions
PPT
Module04
PPTX
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PDF
Lecture Notes Unit5 chapter17 Stored procedures and functions
PPT
PPT
Less09 Data
PPT
MySQL 5.5
PPT
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
ODP
SQL Tunning
PPTX
STORED-PROCEDURE.pptxjsjjdjdjcjcjdkksksksk
PPT
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
PPS
Procedures/functions of rdbms
PDF
Stored procedure Notes By Durgesh Singh
PPT
PHP tips by a MYSQL DBA
PDF
Major features postgres 11
 
PPTX
Developers' New features of Sql server express 2012
ODP
PPTX
Unit 3
ODP
lecture13.ppt
Subqueries views stored procedures_triggers_transactions
Module04
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
Lecture Notes Unit5 chapter17 Stored procedures and functions
Less09 Data
MySQL 5.5
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
SQL Tunning
STORED-PROCEDURE.pptxjsjjdjdjcjcjdkksksksk
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
Procedures/functions of rdbms
Stored procedure Notes By Durgesh Singh
PHP tips by a MYSQL DBA
Major features postgres 11
 
Developers' New features of Sql server express 2012
Unit 3

Recently uploaded (20)

PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Classroom Observation Tools for Teachers
PPTX
Institutional Correction lecture only . . .
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
Cell Types and Its function , kingdom of life
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Pharma ospi slides which help in ospi learning
PDF
Insiders guide to clinical Medicine.pdf
PDF
RMMM.pdf make it easy to upload and study
PPTX
PPH.pptx obstetrics and gynecology in nursing
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
Supply Chain Operations Speaking Notes -ICLT Program
Classroom Observation Tools for Teachers
Institutional Correction lecture only . . .
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Cell Types and Its function , kingdom of life
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
102 student loan defaulters named and shamed – Is someone you know on the list?
Microbial disease of the cardiovascular and lymphatic systems
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Basic Mud Logging Guide for educational purpose
Renaissance Architecture: A Journey from Faith to Humanism
Pharma ospi slides which help in ospi learning
Insiders guide to clinical Medicine.pdf
RMMM.pdf make it easy to upload and study
PPH.pptx obstetrics and gynecology in nursing

Procedures and triggers in SQL

  • 2. 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
  • 3. 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
  • 4. 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?
  • 5. 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
  • 6. Procedures in MySQL - Declaration ● 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
  • 7. 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;
  • 8. Procedures in MySQL - Example 2 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
  • 9. 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', );
  • 10. Functions V/S Procedures MySQL Functions Procedures 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. Its not a DB object. A stored procedure is a database object. A stored procedure saves the query compilation time.
  • 11. 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
  • 12. 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
  • 13. 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 (//)
  • 14. Example Step 3: Change the delimiter back to semicolon (;)
  • 15. Example Step 4: Call the procedure to update the totalsalary for each department
  • 16. Example Step 5: Show the updated total salary in the deptsal table
  • 17. 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
  • 18. 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)
  • 19. Another Example ● Create a procedure to give a raise to all employees
  • 22. 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}
  • 23. SQL Triggers: An Example ● We want to create a trigger to update the total salary of a department when a new employee is hired
  • 24. 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
  • 25. SQL Triggers: An Example totalsalary increases by 90K totalsalary did not change
  • 26. SQL Triggers: An Example ● A trigger to update the total salary of a department when an employee tuple is modified(insert/delete):
  • 27. SQL Triggers: An Example
  • 28. SQL Triggers: An Example ● A trigger to update the total salary of a department when an employee tuple is deleted:
  • 29. SQL Triggers: An Example
  • 30. SQL Triggers ● To list all the triggers you have created: mysql> show triggers;