0% found this document useful (0 votes)
67 views

Stored Procedure

Stored procedures allow users to store SQL statements in the database. They can be called by applications to execute reusable code. Key benefits include increased performance, reduced network traffic, and security. Stored procedures use variables to store results and parameters to pass values. Control structures like IF/ELSE and loops allow conditional execution. Cursors iterate through result sets row by row.

Uploaded by

Sabu K Kuriyan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Stored Procedure

Stored procedures allow users to store SQL statements in the database. They can be called by applications to execute reusable code. Key benefits include increased performance, reduced network traffic, and security. Stored procedures use variables to store results and parameters to pass values. Control structures like IF/ELSE and loops allow conditional execution. Cursors iterate through result sets row by row.

Uploaded by

Sabu K Kuriyan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Stored Procedures

A stored procedure is a segment of declarative SQL statements stored inside the database catalog. A
stored procedure can be invoked by triggers, other stored procedures, and applications such as Java,
Python, PHP.
Stored procedures advantages
● Typically, stored procedures help increase the performance of the applications. Once
created, stored procedures are compiled and stored in the database.
● Stored procedures help reduce the traffic between application and database server
● Stored procedures are reusable and transparent to any applications
● Stored procedures are secure.

Simple Example of a stored procedure

DELIMITER //
CREATE PROCEDURE GetAllProducts()
BEGIN
SELECT * FROM products;
END //
DELIMITER ;

The DELIMITER statement changes the standard delimiter which is a semicolon ( ; ) to another. In
this case, the delimiter is changed from the semicolon( ; ) to double-slashes //. We use the CREATE
PROCEDURE statement to create a new stored procedure. We specify the name of the stored
procedure after the CREATE PROCEDURE statement. The section between BEGIN and END is
called the body of the stored procedure. You put the declarative SQL statements in the body to handle
business logic.
Calling stored procedures
In order to execute a stored procedure, you use the following SQL command:
CALL stored_procedure_name();

Variables in Stored Procedures


A variable is a named data object whose value can change during the stored procedure execution. We
typically use the variables in stored procedures to hold the immediate results. These variables are
local to the stored procedure. You must declare a variable before using it.
Declaring variables
To declare a variable inside a stored procedure, you use the DECLARE statement as follows:

DECLARE variable_name datatype(size) DEFAULT default_value;

First, you specify the variable name after the DECLARE keyword. The variable name must follow
the naming rules of MySQL table column names. Second, you specify the data type of the variable
and its size. A variable can have any MySQL data types such as INT, VARCHAR , and DATETIME.
Third, when you declare a variable, its initial value is NULL. You can assign the variable a default
value using the DEFAULTkeyword.
Once you declared a variable, you can start using it. To assign a variable another value, you use the
SET statement, for example:

DECLARE total_count INT DEFAULT 0;


SET total_count = 10;

Besides the SET statement, you can use the SELECT INTO statement to assign the result of a
query, which returns a scalar value, to a variable.
DECLARE total_products INT DEFAULT 0;
SELECT COUNT(*) INTO total_products FROM products;

Parameters of Stored Procedure


The parameters are used to pass value to stored procedures. In MySQL, a parameter has one of three
modes: IN,OUT, or INOUT.
IN – When you define an IN parameter in a stored procedure, the calling program has to pass an
argument to the stored procedure. When the value of the IN parameter is changed inside the stored
procedure, its original value is retained after the stored procedure ends.
OUT – the value of an OUT parameter can be changed inside the stored procedure and its new
value is passed back to the calling program.
INOUT – an INOUT parameter is a combination of IN and OUT parameters. It means that the
calling program may pass the argument, and the stored procedure can modify the INOUT parameter,
and pass the new value back to the calling program.

The syntax of defining a parameter in the stored procedures is as follows:


MODE param_name param_type(param_size)

The MODE could be IN , OUTor INOUT , depending on the purpose of the parameter in the stored
procedure. The param_name is the name of the parameter. Followed the parameter name is its data
type and size. Like a variable, the data type of the parameter can be any valid MySQL data type. Each
parameter is separated by a comma (,) if the stored procedure has more than one parameter.

IF Statement
The MySQL IF statement allows you to execute a set of SQL statements based on a certain condition
or value of an expression. To form an expression in MySQL, you can combine literals, variables,
operators, and even functions. An expression can return TRUE FALSE, or NULL.

The syntax of the IF statement:

IF expression THEN
statements;
END IF;

In case you want to execute statements when the expression does not evaluate to TRUE, you use the
IF-ELSE statement as follows:

IF expression THEN
statements;
ELSE
else-statements;
END IF;

If you want to execute statements conditionally based on multiple expressions, you use the IF-
ELSEIF-ELSE statement as follows:

IF expression THEN
statements;
ELSEIF elseif-expression THEN
elseif-statements;
...
ELSE
else-statements;
END IF;

If the expression evaluates to TRUE , the statements in the IF branch executes; Otherwise, MySQL
will check the elseif-expression and execute the elseif-statements in the ELSEIF branch if the
elseif_expression evaluates to TRUE. The IF statement may have multiple ELSEIF branches to check
multiple expressions. If no expression evaluates to TRUE, the else-statements in the ELSE branch
will execute.
Loop in Stored Procedures
MySQL provides loop statements that allow you to execute a block of SQL code repeatedly based on
a condition. There are three loop statements in MySQL: WHILE, REPEAT and LOOP.
WHILE loop
The syntax of the WHILEstatement is as follows:

WHILE expression DO
statements
END WHILE

The WHILE loop checks the expressionat the beginning of each iteration. If the expressionevaluates
to TRUE, MySQL will execute statementsbetween WHILEand END WHILE until the
expressionevaluates to FALSE. The WHILE loop is called pretest loop because it checks the
expression before the statements execute.
Example to find sum of first N natural numbers using while loop

DROP PROCEDURE IF EXISTS NSUM;


DELIMITER $$
CREATE PROCEDURE NSUM(IN N INT(2))
BEGIN
DECLARE I INT(2) DEFAULT 1;
DECLARE SUM INT(4) DEFAULT 0;
WHILE I<=N DO
SET SUM=SUM+I;
SET I=I+1;
END WHILE;
SELECT CONCAT("SUM = ",SUM);
END $$
DELIMITER ;

REPEAT loop
The syntax of the REPEAT loop statement is as follows:

REPEAT
statements;
UNTIL expression
END REPEAT

First, MySQL executes the statements, and then it evaluates the expression. If the expressionevaluates
to FALSE, MySQL executes the statements repeatedly until the expression evaluates to TRUE.
Because the REPEAT loop statement checks the expression after the execution of statements, the
REPEATloop statement is also known as the post-test loop.
Example to List number upto n using UNTIL Loop

DELIMITER $$
DROP PROCEDURE IF EXISTS LIST $$
CREATE PROCEDURE LIST(IN N INT(4))
BEGIN
DECLARE I INT(2) DEFAULT 1;
DECLARE OUTSTR VARCHAR(40) DEFAULT "";
REPEAT
SET OUTSTR=CONCAT(OUTSTR,I,",");
SET I=I+1;
UNTIL I=N
END REPEAT;
SELECT OUTSTR;
END $$
DELIMITER ;

LOOP, LEAVE and ITERATE statements


The LEAVEstatement allows you to exit the loop immediately without waiting for checking the
condition. The ITERATEstatement allows you to skip the entire code under it and start a new iteration.
MySQL also gives you a LOOPstatement that executes a block of code repeatedly with an additional
flexibility of using a loop label.

Example to list Even numbers using loop, iterate and leave

DROP PROCEDURE IF EXISTS listeven;


DELIMITER $$
CREATE PROCEDURE listeven(IN N INT(2))
BEGIN
DECLARE I INT(3) DEFAULT 0;
DECLARE outstr varchar(40) DEFAULT "";
looplabel:
LOOP
SET I=I+1;
IF I MOD 2 = 0 THEN
set outstr=CONCAT(outstr,",",I);
ELSE
ITERATE looplabel;
END IF;

IF (I>N) THEN
LEAVE looplabel;
END IF;
END LOOP;
SELECT outstr;
END $$
DELIMITER ;

MySQL cursor
A cursor allows you to iterate a set of rows returned by a query and process each row accordingly.
MySQL cursor is read-only, non-scrollable and asensitive.
Working with MySQL cursor
First, you have to declare a cursor by using the DECLARE statement:
DECLARE cursor_name CURSOR FOR SELECT_statement;
Next, you open the cursor by using the OPEN statement. The OPEN statement initializes the result
set for the cursor, therefore, you must call the OPEN statement before fetching rows from the result
set.
OPEN cursor_name;
Then, you use the FETCH statement to retrieve the next row pointed by the cursor and move the
cursor to the next row in the result set.
FETCH cursor_name INTO variables list;
Finally, you call the CLOSE statement to deactivate the cursor and release the memory associated
with it as follows:
CLOSE cursor_name;
When working with MySQL cursor, you must also declare a NOT FOUND handler to handle the
situation when the cursor could not find any row. Because each time you call the FETCH statement,
the cursor attempts to read the next row in the result set. When the cursor reaches the end of the
result set, it will not be able to get the data, and a condition is raised. The handler is used to handle
this condition.
To declare a NOT FOUND handler, you use the following syntax:
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
The finished is a variable to indicate that the cursor has reached the end of the result set. Notice that
the handler declaration must appear after variable and cursor declaration inside the stored
procedures.

Example

CREATE TABLE STUDENTS(SID INT(4) PRIMARY KEY,SNAME VARCHAR(30),SCIENCE


INT(3), MATHEMATICS INT(3), LANGUAGE INT(3));
INSERT INTO STUDENTS VALUES(101,'SANAL',32,34,32),
(103,'BINIL',35,28,27),(104,'RENIL',29,2,32);

CREATE TABLE TOTALMARK(SID INT(4),TOTAL INT(4));

DELIMITER $$
DROP PROCEDURE IF EXISTS CALCTOTAL $$

CREATE PROCEDURE CALCTOTAL()


BEGIN
DECLARE ID INT(4);
DECLARE N VARCHAR(30);
DECLARE SUB1 INT(4);
DECLARE SUB2 INT(4);
DECLARE SUB3 INT(4);
DECLARE T INT(4);
DECLARE FINISHED INT(1) DEFAULT 0;
DECLARE C1 CURSOR FOR SELECT * FROM STUDENTS;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET FINISHED=1;
OPEN C1;

LOOPLABEL: LOOP
FETCH C1 INTO ID,N,SUB1,SUB2,SUB3;
IF FINISHED=1 THEN
LEAVE LOOPLABEL;
END IF;
SET T=SUB1+SUB2+SUB3;
INSERT INTO TOTALMARK VALUES(ID,T);
END LOOP LOOPLABEL;
END $$
DELIMITER ;

Stored Function
Stored function is a special kind stored program that returns a single value. You use stored functions
to encapsulate common formulas or business rules that are reusable among SQL statements or
stored programs. Different from a stored procedure, you can use a stored function in SQL
statements wherever an expression is used. This helps improve the readability and maintainability
of the procedural code.

MySQL stored function syntax


CREATE FUNCTION function_name(param1,param2,…)
RETURNS datatype
[NOT] DETERMINISTIC
statements

First, you specify the name of the stored function after CREATE FUNCTION clause.
Second, you list all parameters of the stored function inside the parentheses. By default, all parameters
are the IN parameters.
Third, you must specify the data type of the return value in the RETURNS statement. It can be any
valid MySQL data types.
Fourth, for the same input parameters, if the stored function returns the same result, it is considered
deterministic; otherwise, the stored function is not deterministic. You have to decide whether a stored
function is deterministic or not.
Fifth, you write the code in the body of the stored function. It can be a single statement or a compound
statement. Inside the body section, you have to specify at least onr RETURN statement to returns a
value to the caller. Whenever the RETURN statement is reached, the stored function’s execution is
terminated immediately.

Simple Example- Write a function to find factorial of a number


DROP FUNCTION IF EXISTS FACT;
DELIMITER $$

CREATE FUNCTION FACT(N INT(2)) RETURNS INT(6)


BEGIN
DECLARE I INT(2) DEFAULT 1;
DECLARE F INT(6) DEFAULT 1;
WHILE I<=N DO
SET F=F*I;
SET I=I+1;
END WHILE;
RETURN F;
END $$

SQL trigger
A SQL trigger is a set of SQL statements stored in the database catalog. A SQL trigger is executed or
fired whenever an event associated with a table occurs e.g., insert, update or delete. A SQL trigger is
a special type of stored procedure, it is not called directly 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 whereas a stored procedure must be called explicitly.
Advantages of using SQL triggers
● SQL triggers provide an alternative way to check the integrity of data.
● SQL triggers can catch errors in business logic in the database layer.
● By using SQL triggers, you don’t have to wait to run the scheduled tasks because the triggers
are invoked automatically before or after a change is made to the data in the tables.
● SQL triggers are very useful to audit the changes of data in tables.
In MySQL, a trigger is a set of SQL statements that is invoked automatically when a change is made
to the data on the associated table. A trigger can be defined to be invoked either before or after the
data is changed by INSERT, UPDATE or DELETE statement.
you can define a maximum of six triggers for each table.

BEFORE INSERT – activated before data is inserted into the table.


AFTER INSERT – activated after data is inserted into the table.
BEFORE UPDATE – activated before data in the table is updated.
AFTER UPDATE – activated after data in the table is updated.
BEFORE DELETE – activated before data is removed from the table.
AFTER DELETE – activated after data is removed from the table.
You must use a unique name for each trigger associated with a table. However, you can have the same
trigger name defined for different tables though it is a good practice.
In order to create a new trigger, you use the CREATE TRIGGER statement.
CREATE TRIGGER trigger_name trigger_time trigger_event
ON table_name
FOR EACH ROW
BEGIN
...
END;
You put the trigger name after the CREATE TRIGGER statement. Trigger activation time can be
BEFORE or AFTER. You use the 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 the change is made. The trigger
event can be INSERT, UPDATE or DELETE. This event causes the trigger to be invoked. 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. You place the SQL statements between BEGIN and
END block. This is where you define the logic for the trigger.

Raising Error Conditions with MySQL SIGNAL


You use the SIGNAL statement to return an error or warning condition to the caller from a stored
program e.g., stored procedure, stored function, trigger or event. The SIGNAL statement provides
you with control over which information for returning such as value and messageSQLSTATE.

The following illustrates syntax of the SIGNAL statement:

SIGNAL SQLSTATE | condition_name;


SET condition_information_item_name_1 = value_1,
condition_information_item_name_1 = value_2, etc;

Following the SIGNAL keyword is a SQLSTATE value. To provide the caller with information, you
use the SET clause. If you want to return multiple condition information item names with values, you
need to separate each name/value pair by a comma. The condition_information_item_name can be
MESSAGE_TEXT, MYSQL_ERRORNO, CURSOR_NAME , etc.
Trigger Examples

STUDENTS
Field Type
SID INT(4)
PRIMARY KEY
SNAME VARCHAR(30)
PROGRAM VARCHAR(30)
SCIENCE INT(3)
MATEMATICSS INT(3)
LANGUAGE INT(3)

AUDIT_STUDENTS
Field Type
ID INT(4) AUTO_INCREMENT
PRIMARY KEY
SID INT(4)
CHANGEDATE DATE

Trigger to log the changes of CT students in audit_students table

DELIMITER $$
CREATE TRIGGER after_update_students AFTER UPDATE ON students
FOR EACH ROW
BEGIN
if old.program='CT' then
INSERT INTO audit_students(sid,changedate) values(old.sid,now());
end if;
END $$

Trigger to validate the values in the marks field

CREATE TRIGGER before_insert_students BEFORE INSERT ON students


FOR EACH ROW
BEGIN
if new.science>100 or new.mathematics>100 or new.language>100 then
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='marks should be less than 100';
end if;
END $$

DELIMITER ;

The term used in the SQL standard for stored procedures is persistent stored modules because these
programs are stored persistently by the DBMS. Stored procedures are useful in the following
circumstances:
If a database program is needed by several applications, it can be stored at the server and invoked by
any of the application programs.
Executing a program at the server can reduce data transfer and communication cost between the client
and server in certain situations.
These procedures can enhance the modeling power provided by views by allowing more complex
types of derived data to be made available to the database users.
The general form of declaring stored procedures is as follows:

CREATE PROCEDURE <procedure name> (<parameters>)


<local declarations>
<procedure body> ;

In general, each parameter should have a parameter type that is one of the SQL data types. Each
parameter should also have a parameter mode, which is one of IN , OUT , or INOUT . These
correspond to parameters whose values are input only, output (returned) only, or both input and output,
respectively.
The CALL statement in the SQL standard can be used to invoke a stored procedure
CALL <procedure or function name> (<argument list>) ;

For declaring a function, a return type is necessary, so the declaration form is


CREATE FUNCTION <function name> (<parameters>)
RETURNS <return type>
<local declarations>
<function body> ;

Stored function is a special kind stored program that returns a single value. You use stored functions
to encapsulate common formulas or business rules that are reusable among SQL statements or stored
programs. Different from a stored procedure, you can use a stored function in SQL statements
wherever an expression is used. This helps improve the readability and maintainability of the
procedural code.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy