Procedures in MySql
Procedures in MySql
So if you have an SQL query that you write over and over again, save it as
a stored procedure, and then just call it to execute it.
Example -1
CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;
Example
EXEC SelectAllCustomers;
Example
EXEC SelectAllCustomers @City = 'Trichy';
Stored Procedure With Multiple Parameters
Setting up multiple parameters is very easy. Just list each parameter and
the data type separated by a comma as shown below.
Example- 3
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30),
@PostalCode nvarchar(10)
AS
SELECT * FROM Customers WHERE City = @City AND PostalCode =
@PostalCode
GO;
Example
EXEC SelectAllCustomers @City = 'Trichy', @PostalCode = 620015';
FUNCTION
The CREATE FUNCTION statement is used for creating a stored function
and user-defined functions. A stored function is a set of SQL statements
that perform some operation and return a single value.
1. function_name:
It is the name by which stored function is called. The name should not
be same as native(built_in) function. In order to associate routine
explicitly with a specific database function name should be given
as database_name.func_name.
2. func_parameter:
It is the argument whose value is used by the function inside its body.
You can’t specify to these parameters IN, OUT, INOUT. The
parameter declaration inside parenthesis is provided
as func_parameter type. Here, type represents a valid Mysql
datatype.
3. datatype:
It is datatype of value returned by function.
4. characteristics:
The CREATE FUNCTION statement is accepted only if at least one of
the characterisitics { DETERMINISTIC, NO SQL, or READS SQL DATA }
is specified in its declaration.
Mysql Statements
RETURN expression;
END
The function body must contain one RETURN statement.
Example:
Consider following Employee Table-
Hawthorn
4 Susan e 2002-04-24
We have to find the number of years the employee has been in the
company-
DELIMITER //
//
DELIMITER ;
Calling of above function:
Select emp_id, fname, lname, no_of_years(start_date) as 'years' from
employee;
Output:
EMP_ID FNAME LNAME YEARS
1 Michael Smith 18
EMP_ID FNAME LNAME YEARS
2 Susan Barker 17
3 Robert Tvler 19
4 Susan Hawthorne 17