How To Create Stored Procedures
How To Create Stored Procedures
• In the Object Explorer, expand the database for which you want to create the stored procedure, expand its
Programmability node, right-click Stored Procedures, and click New Stored Procedure... A Query window with a skeleton
syntax would be displayed. You can then modify that code using the techniques we will learn in this lesson
• Open an empty Query window associated with the database for which you want to create the stored procedure and display
the Templates Explorer. In the Templates Explorer, expand the Stored Procedure node. Drag Create Stored Procedure and
drop it in the Query window
• Open an empty Query window associated with the database for which you want to create the stored procedure and enter
the necessary code
The simplest syntax to create a stored procedure in Transact-SQL is:
• The name of a procedure can be any string that follows the rules we reviewed for naming the functions
• Refrain from starting the name of a stored procedure with sp_ because it could conflict with some of the stored procedures
that already ship with Microsoft SQL Server
When creating a stored procedure, you can precede its name by a schema name. After the name of the procedure, type
the AS keyword. The section, group of words, or group of lines after the AS keyword is the body of the stored procedure. It states
what you want the procedure to do or what you want it to produce. It is important to keep in mind that there are many other issues
related to creating a stored procedure but we will ignore them for now.
Probably the simplest procedure you can create would consist of selecting fields from a table. This is done with
the SELECT operator. It uses the techniques we reviewed for data selection. For example, to create a stored procedure that would
hold a list of students from a table named Students, you would create the procedure as follows:
Besides SELECT operations, in a stored procedure, you can perform any of the database operations we have applied so far. These
include creating and maintaining records, etc.
To get the results of creating a stored procedure, you must execute it (in other words, to use a stored procedure, you must call it).
To execute a stored procedure, you use the EXECUTE keyword followed by the name of the procedure. Although there are some
other issues related to executing a stored procedure, for now, we will consider that the simplest syntax to call a procedure is:
EXEC/EXECUTE [SchemaName.]ProcedureName
If you have a stored procedure named GetStudentIdentification, to execute it, you would type:
EXECUTE GetStudentIdentification
You can also precede the name of the procedure with its schema. Here is an example:
EXECUTE Registration.GetStudentIdentification;
You can also precede the name of the schema with the name of the database. Here is an example:
EXECUTE rosh.Registration.GetStudentIdentification;
Practical Learning: Executing a Stored Procedure
1. Click inside the top section of the Query window and press Ctrl + A to select everything
2. To execute the stored procedure, type the following
3. EXECUTE Management.ShowInformation;
GO
4. To execute the stored procedure, right-click inside the top section of the Query window and click Execute
5. Click inside the top section of the Query window and press Ctrl + A
To start, a developer who has to create one ore more stored procedures must have the CREATE PROCEDURE permission on the
database that will own the procedure. Also, he or she must have theALTER permissions. You must also coordinate the permissions
of the user on the objects used by the stored procedure.
• If you want your own account to be used, use WITH EXECUTE AS SELF. This is the default for a stored procedure. In
this case, your user name will be stored with the procedure and the databaseengine will call it when the sotred procedure is
executed.
• If you want the account of the user who is executing the procedure to be used, use WITH EXECUTE AS CALLER. In
this case, when the user starts executing the procedure, the database engine will check whether the user has the appropriate
permissions. If so, the stored procedure would execute. Otherwise, he will be denied.
• If you want the account of the owner of the database to be used, use WITH EXECUTE AS OWNER.
• If you want to specify the account that will be used when executing the schema, use WITH EXECUTE AS, followed by
the user name. Here is an example:
CREATE USER Patricia FOR LOGIN [Central\pkatts];
GO
CREATE PROCEDURE Registration.GetContactInformation
WITH EXECUTE AS N'Patricia'
AS
SET NOCOUNT ON
SELECT FirstName, LastName, ParentsNames
FROM Registration.Students;
GO
Managing Procedures
Introduction
When a stored procedure executes, the database engine must keep sending messages back and forth between the server and the
client. These relentless interactions create overhead on the processing and in most cases are not necessary. To avoid them, after the
AS keyword, add a SET NOCOUNT ON expression before starting the body of the stored procedure. The formula to follow is:
To ask the database engine to check the stored procedure and recompile it the next time it is executed, when creating the procedure,
before the AS keyword, add a WITH RECOMPILE expression. The formula to follow is:
There are various types of stored procedures, some of which are considered temporary. Those types of procedures delete
themselves when not needed anymore, such as when the person who created the stored procedure disconnects from the database or
shuts down the computer. Otherwise, to delete a stored procedure, you can use either the Object Explorer or SQL. As mentioned
with tables, even if you create a stored procedure using the Object Explorer, you can delete it using SQL and vice-versa.
To delete a stored procedure in the Object Explorer, after expanding its database, its Programmability, and its Stored Procedure
nodes, right-click the stored procedure and click Delete. You can also click it in the Object Explorer to select it and then press
Delete. The Delete Object dialog box would come up to let you make a decision.
EXEC rosh.Registration.GetStudentsAges;
GO
Arguments and Parameters
Introduction
All of the stored procedures we have created and used so far assumed that the values they needed were already in a table of the
database. In some cases, you may need to create a stored procedure that involves values that are not part of the database. On such a
scenario, for the stored procedure to carry its assignment, you would supply it with one or more values.
An external value that is provided to a stored procedure is called a parameter. When you create a stored procedure, you must also
create the parameter if you judge it necessary. When a procedure's creation is equipped with a parameter, it is said that the stored
procedure takes an argument. A stored procedure can also take more than one argument.
When you execute a stored procedure that takes one or more arguments, you must provide a value for each argument. In this case,
you are said to pass a value for the argument. There are cases when you don't have to provide an argument.
Passing Arguments
To create a stored procedure that takes an argument, type the formula CREATE PROCEDURE orCREATE PROC followed by
the name of the procedure, then type the name of the argument starting with @. The parameter is created like a column of a table.
That is, a parameter must have a name, a data type and an optional length. Here is the syntax you would use:
Another type of stored procedure can be made to take more than one parameter. In this case, create the parameters in the section before the AS keyword, separated by
(a) comma(s). The syntax you would use is:
USE ROSH;
GO
CREATE PROCEDURE Registration.IdentifyStudentsByState
@Gdr nvarchar(20),
@StateOrProvince char(2)
AS
BEGIN
SELECT FullName = LastName + ', N' + FirstName,
DATEDIFF(year, DateOfBirth, GETDATE()) AS Age,
Gender
FROM Registration.Students
WHERE (Gender = @Gdr) AND (State = @StateOrProvince);
END
GO
When calling a stored procedure that takes more than one parameter, you must still provide a value for each parameter but you have two alternatives. The simplest
technique consists of providing a value for each parameter in the exact order they appear in the stored procedure. Here is an example:
USE ROSH;
GO
EXEC rosh.Registration.IdentifyStudentsByState N'Female', N'MD';
GO
This would produce:
Alternatively, you can provide the value for each parameter in the order of your choice. Consider the following stored procedure that takes 3 arguments:
USE ROSH;
GO
CREATE PROCEDURE Registration.IdentifySomeStudents
@Gdr nvarchar(20),
@StateOrProvince nchar(2),
@HomeStatus bit
AS
BEGIN
SET NOCOUNT ON
SELECT FullName = LastName + N', ' + FirstName,
DATEDIFF(year, DateOfBirth, GETDATE()) AS Age,
Gender
FROM Registration.Students
WHERE (Gender = @Gdr) AND
(State = @StateOrProvince) AND
(SingleParentHome = @HomeStatus);
END
GO
When calling this type of procedure, you can type the name of each parameter and assign it the corresponding value. Here is an example:
USE ROSH;
GO
EXEC Registration.IdentifySomeStudents @HomeStatus=1, @StateOrProvince=N'MD', @Gdr=N'Female';
GO
Here is an example of executing the procedure:
Practical Learning: Executing an Argumentative Procedure
1. To execute the stored procedure, type the following:
2. USE WattsALoan1;
3. GO
4. EXECUTE Loans.SpecifyCurrentBalance N'03/25/2004', 2, 1, 249.08;
5. GO
6. EXECUTE Loans.SpecifyCurrentBalance N'01/30/2006', 2, 5, 611.93;
7. GO
8. EXECUTE Loans.SpecifyCurrentBalance N'04/20/2004', 1, 1, 249.08;
9. GO
10. EXECUTE Loans.SpecifyCurrentBalance N'10/28/2006', 2, 4, 134.38;
GO
11. To execute, press F5
12. To see a list of payments made on different loans, type the following:
13. SELECT ALL * FROM Loans.Payments;
GO
14. To see the result, on the main menu, click Query -> Execute
15. Click inside the top section of the Query window and press Ctrl + A
Default Arguments
Imagine you create a database for a department store and a table that holds the list of items sold in the store:
To create a stored procedure that takes an argument that carries a default value, after declaring the value, on its right side, type = followed by the desired value. Here is
an example applied to the above database:
If the default value doesn't apply to your current calculation, you can provide a value for the argument. Here is an example:
On the other hand, you can ask the database engine to get the default value. To do this, pass the argument as DEFAULT. Here is an example:
You can create a stored procedure that takes more than one argument with default values. To provide a default value for each argument, after declaring it, type the
desired value to its right side. Here is an example of a stored procedure that takes two arguments, each with a default value:
When calling a stored procedure that takes more than one argument and all arguments have default values, you don't need to provide a value for each argument, you
can provide a value for only one or some of the arguments. The above procedure can be called with one argument as follows:
We saw that, when calling a stored procedure that takes more than one argument, you didn't have to provide the values of the arguments in the exact order they
appeared in the procedure, you just had to type the name of each argument and assign it the desired value. In the same way, if a stored procedure takes more than one
argument and some of the arguments have default values, when calling it, you can provide the values in the order of your choice, by typing the name of each argument
and assigning it the desired value. Based on this, the above stored procedure can be called with only the value of the second argument as follows: