Professional Documents
Culture Documents
Writing external scripts to perform complex data handling is a tedious affair. The best way to automate tasks straightaway into the server is by using
Stored Procedures. It is very useful to make them as flexible as possible, as it facilitates easy identification of any errors and can be used for
executing a variety of tasks as well.
Stored procedures are set of SQL commands that are stored in the database data server. After the storing of the commands is done, the tasks can be
performed or executed continuously, without being repeatedly sent to the server. This also helps in decreasing the traffic in the networks and also
reduces the CPU load.
For few years, Oracle and Microsoft SQL servers were having one upper hand over MySQL by having the facility to use the advantage of Stored
Procedures. But this advantage has become a thing of the past now. With MySQL 5, you can use Stored Procedures the way you have been utilizing
with other servers.
CREATE
[DEFINER = { user | CURRENT_USER }]
PROCEDURE sp_name ([proc_parameter[,...]])
[characteristic ...] routine_body
CREATE
[DEFINER = { user | CURRENT_USER }]
FUNCTION sp_name ([func_parameter[,...]])
RETURNS type
[characteristic ...] routine_body
proc_parameter:
[ IN | OUT | INOUT ] param_name type
func_parameter:
param_name type
type:
Any valid MySQL data type
characteristic:
LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'
routine_body:
Valid SQL procedure statement
Application
MySQL Stored Procedures can be applied in absolutely any place. Right from complex applications to simple procedures, these stored procedures can
be utilized in absolutely any place.
Few of the many places that MySQL Stored procedures can be used are:
• When diverse client applications are structured using various languages in different platforms
• When security is of highest importance, like in financial institutions, the users and applications would have no direct access to the database tables.
This provides excellent secured environment.
• When very few database servers service the client machines, thereby providing efficient performance
Though not as mature as Oracle, DB2 or the SQL Server, the MySQL Stored Procedures is definitely worth a try. If the structure of the database is the
same, the same stored procedures can be used for all.
A simple example for MySQL Stored Procedure
To calculate the area of a circle with given radius R, the following commands can be given
delimiter //
deterministic
begin
declare A double;
set A = R * R * pi();
return A;
end
//
delimiter ;
And to call it from php code to display the area of a circle with radius 22cm,
<?
$area = mysql_result($rs_area,0,0);
echo “The area of the circle with radius 22cm is ”.$area.” sq.cm”;
?>
Our Sites: Tutorial Buzz | How To Tree | Recipe Voice | Golf Twist | DIY Click | Movie Lizard | Halloween Twist
<
The result is
Job
Analyst
EXISTS Function
The EXISTS function checks the inner query of a subquery and evaluates to
its result contains at least one row. The syntax of the EXISTS function is
EXAMPLE 5.36
Get the names of all employees with employee numbers greater than or equal to 10000.
USE sample
SELECT emp_fname, emp_lname
FROM (SELECT *
FROM employee
WHERE emp_no >= 10000 ) AS empno_10000
The result is
emp_fname emp_lname
Matthew Smith
Ann Jones
John Barrimore
A function is a relatively small task that should be performed aside but can be accessed any time
to give a result. In Transact-SQL, a function is considered an object. Based on this, you must
create a function and execute it before using it. The function then becomes part of a database and
it can be accessed.
1.
Practical Learning: Introducing Functions
Make sure you have a user account named pkatts (created in Lesson 1).
Make sure you created a login for the pkatts account (created in Lesson 3).
Start the SQL Server Management Studio
2. To create a new database, right-click Databases and click New Database...
3. In the Name text box, type RealEstate1
4. Set the owner to ComputerName\pkatts (Windows XP or Vista) or DomainName\pkatts
(Windows Server)
5. Set the Paths to C:\Microsoft SQL Server Database Development
6. Click OK
7. In the Object Explorer, Expand the Databases node followed by the RealEstate1 node
8. Under RealEstate1, right-click Security, position the mouse on New, and click Schema...
9. Type the name as Payroll and press Enter
Function Creation Fundamentals
There are various ways you can start the creating of a function:
• A name will start with either an underscore or a letter. Examples are _n, act, or Second
• After the first character as an underscore or a letter, the name will have combinations of underscores, letters, and
digits. Examples are _n24, act_52_t
• A name will not include special characters such as !, @, #, $, %, ^, &, or *
• We will avoid using spaces in a name, with few exceptions
• If the name is a combination of words, each word will start in uppercase. Examples are DateHired, _RealSport, or
DriversLicenseNumber
After specifying the type of value that the function would return, you can create a body for the function. The body of a
function starts with the BEGIN and ends with the END keywords. Here is an example:
END
Optionally, you can type the AS keyword before the BEGIN keyword:
END
Between the BEGIN and END keywords, which is the section that represents the body of the function, you can define the
assignment the function must perform. After performing this assignment, just before the END keyword, you must specify
the value that the function returns. This is done by typing the RETURN keyword followed by an expression. A sample
formula is:
Here is an example
1.
Practical Learning: Creating Functions
In the Object Explorer, right-click RealEstate1 and click New Query...
2. To create a function, type the following statement:
Function Calling
After a function has been created, you can use the value it returns. Using a function is also referred to as calling it. To call
a function, you must qualify its name. To do this, type the name of the database in which it was created, followed by the
period operator, followed by dbo, followed by the period operator, followed by the name of the function, and its
parentheses. The formula to use is:
DatabaseName.dbo.FunctionName()
Because a function returns a value, you can use that value as you see fit. For example, you can use either PRINT or
SELECT to display the function's value in a query window. Here is an example that calls the above Addition() function:
PRINT Exercise.dbo.GetFullName();
As an alternative, to call a function, in the Object Explorer, right-click its name, position the mouse on Script Function As,
SELECT To, and click New Query Editor Window.
1.
Practical Learning: Calling a Function
In the Object Explorer, right-click RealEstate1 and click New Query
2. To execute the function we just created, execute the following statement:
PRINT RealEstate1.dbo.CalculateWeeklySalary();
GO
Function Maintenance
Introduction
Because a function in Transact-SQL is treated as an object, it may need maintenance. Some of the actions you would take
include renaming, modifying, or deleting a function.
Renaming a Function
If you create a function and execute it, it is stored in the Scalar-Valued Functions node with the name you gave it. If you
want, you can change that name but keep the functionality of the function.
To rename a function, in the Object Explorer, right-click it and click Rename. Type the desired new name and press Enter.
Deleting a Function
If you create a function and decide that you don't need it any more, you can delete it.
To delete a function in the Object Explorer, locate the function in the Functions section, right-click it and click Delete. The
Delete Object dialog box would come up. If you still want to delete the function, click OK; otherwise, click Cancel.
• In a query window, type DROP FUNCTION followed by the name of the function and execute the statement
• In the Object Explorer, right-click the name of the function, position the mouse on Script Function As, DROP To, and
click New Query Editor Window
• Open a new query window associated with the database that contains the function. Display the Templates Explorer
and expand the Function node. Drag the Drop Function node and drop it in the empty query window
1.
Practical Learning: Deleting a Function
In the Object Explorer, under the Scalar-Valued Functions node, right-click dbo.CalculateWeeklySalary and click
Delete
2. In the Delete Object dialog box, click OK
Modifying a Function
As mentioned already, in the body of the function, you define what the function is supposed to take care of. As a
minimum, a function can return a simple number, typed on the right side of the RETURN keyword. Here is an example:
1.
Practical Learning: Declaring Local Variables
In the Calculate query window, change the code as follows (notice the addition of the schema):
Function Arguments
Introduction
In order to carry its assignment, a function can be provided with some values. Put it another way, when you create a
function, instead of, or in addition to, local variables, you may want the code that will call the function to provide the
values needed to perform the assignment. For example, imagine you want to create a function that would generate
employees email addresses when a user has entered a first and last name. At the time you are creating the function, you
cannot know or predict the names of employees, including those who have not even been hired yet. In this case, you can
write the whole function but provide one or more placeholders for values that would be supplied when the function is
called.
An external value that is provided to a function is called a parameter. A function can also take more than one parameter.
Therefore, when you create a function, you also decide whether your function would take one or more parameters and
what those parameters, if any, would be.
A Parameterized Function
We have already seen that a function's name is also followed by parentheses. If the function doesn't use an external
value, its parentheses can be left empty. If a function will use an external value, when you create the function, you must
specify a name and the type of value of the parameters. The name of the parameter is created with the @ sign, like a
variable as we saw in the previous lesson. Here is an example:
When a function takes a parameter, in the body of the function, you can use the parameter as if you knew its value, as
long as you respect the type of that value. Here is an example:
Once again, in the body of the function, you can use the parameters as if you already knew their value. You can also
declare local variables and involve them with parameters as you see fit. Here is an example:
When calling a function that takes more than one parameter, in the parentheses of the function, provide a value for each
parameter, in the exact order they appear in the parentheses of the function. Here is an example:
You can also pass the names of already declared and initialized variables. Here is an example that calls the above
function:
RETURN @Weekly
END;
4. GO Press F5 to create the function
5. Delete the code in the window and replace it with the following: