SQL Server Stored Procedure Tutorial
SQL Server Stored Procedure Tutorial
Overview
A stored procedure is nothing more than prepared SQL code that you save so you can reuse the code
over and over again. So if you think about a query that you write over and over again, instead of
having to write that query each time you would save it as a stored procedure and then just call the
stored procedure to execute the SQL code that you saved as part of the stored procedure.
In addition to running the same SQL code over and over again you also have the ability to pass
parameters to the stored procedure, so depending on what the need is the stored procedure can act
accordingly based on the parameter values that were passed.
Take a look through each of these topics to learn how to get started with stored procedure
development for SQL Server.
You can either use the outline on the left or click on the arrows to the right or below to scroll through
each of these topics.
Explanation
Some of the topics we will cover include:
Explanation
Before you create a stored procedure you need to know what your end result is, whether you are
selecting data, inserting data, etc..
In this simple example we will just select all data from the Person.Address table that is stored in the
AdventureWorks database.
So the simple T-SQL code excuting in the AdventureWorks database would be as follows which will
return all rows from this table.
USE AdventureWorks
GO
EXEC dbo.uspGetAddress
-- or
EXEC uspGetAddress
--or just simply
uspGetAddress
When creating a stored procedure you can either use CREATE PROCEDURE or CREATE
PROC. After the stored procedure name you need to use the keyword "AS" and then the rest is just
the regular SQL code that you would normally execute.
One thing to note is that you cannot use the keyword "GO" in the stored procedure. Once the SQL
Server compiler sees "GO" it assumes it is the end of the batch.
Also, you can not change database context within the stored procedure such as using "USE dbName"
the reason for this is because this would be a separate batch and a stored procedure is a collection of
only one batch of statements.
How to create a SQL Server stored procedure
with parameters
Overview
The real power of stored procedures is the ability to pass parameters and have the stored procedure
handle the differing requests that are made. In this topic we will look at passing parameter values to a
stored procedure.
Explanation
Just like you have the ability to use parameters with your SQL code you can also setup your stored
procedures to accept one or more parameter values.
One Parameter
In this example we will query the Person.Address table from the AdventureWorks database, but
instead of getting back all records we will limit it to just a particular city. This example assumes
there will be an exact match on the City value that is passed.
USE AdventureWorks
GO
USE AdventureWorks
GO
Procedure or function 'uspGetAddress' expects parameter '@City', which was not supplied.
USE AdventureWorks
GO
USE AdventureWorks
GO
Multiple Parameters
Setting up multiple parameters is very easy to do. You just need to list each parameter and the data
type separated by a comma as shown below.
USE AdventureWorks
GO
Explanation
Setting up output paramters for a stored procedure is basically the same as setting up input
parameters, the only difference is that you use the OUTPUT clause after the parameter name to
specify that it should return a value. The output clause can be specified by either using the keyword
"OUTPUT" or just "OUT". For these examples we are still using the AdventureWorks database, so all
the stored procedures should be created in the AdventureWorks database.
Simple Output
CREATE PROCEDURE dbo.uspGetAddressCount @City nvarchar(30), @AddressCount int
OUTPUT
AS
SELECT @AddressCount = count(*)
FROM AdventureWorks.Person.Address
WHERE City = @City
Or it can be done this way:
Explanation
If you are not familiar with the Try...Catch paradigm it is basically two blocks of code with your
stored procedures that lets you execute some code, this is the Try section and if there are errors they
are handled in the Catch section.
Let's take a look at an example of how this can be done. As you can see we are using a basic
SELECT statement that is contained within the TRY section, but for some reason if this fails it will
run the code in the CATCH section and return the error information.
Explanation
SQL Server offers two types of comments in a stored procedure; line comments and block
comments. The following examples show you how to add comments using both
techniques. Comments are displayed in green in a SQL Server query window.
Line Comments
To create line comments you just use two dashes "--" in front of the code you want to comment. You
can comment out one or multiple lines with this technique.
-- this procedure gets a list of addresses based on the city value that is passed
CREATE PROCEDURE dbo.uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM Person.Address
WHERE City = @City -- the @City parameter value will narrow the search criteria
GO
Block Comments
To create block comments the block is started with "/*" and ends with "*/". Anything within that
block will be a comment section.
/*
-this procedure gets a list of addresses based
on the city value that is passed
-this procedure is used by the HR system
*/
CREATE PROCEDURE dbo.uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM Person.Address
WHERE City = @City
GO
/*
-this procedure gets a list of addresses based
on the city value that is passed
-this procedure is used by the HR system
*/
CREATE PROCEDURE dbo.uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM Person.Address
WHERE City = @City -- the @City parameter value will narrow the search criteria
GO
Explanation
SQL Server uses object names and schema names to find a particular object that it needs to work
with. This could be a table, stored procedure, function ,etc...
It is a good practice to come up with a standard naming convention for you objects including stored
procedures.
Standardize on a Prefix
It is a good idea to come up with a standard prefix to use for your stored procedures. As mentioned
above do not use "sp_", so here are some other options.
usp_
sp
usp
etc...
To be honest it does not really matter what you use. SQL Server will figure out that it is a stored
procedure, but it is helpful to differentiate the objects, so it is easier to manage.
So based on the actions that you may take with a stored procedure, you may use:
Insert
Delete
Update
Select
Get
Validate
etc...
So here are a few examples:
uspInsertPerson
uspGetPerson
spValidatePerson
SelectPerson
etc...
Another option is to put the object name first and the action second, this way all of the stored
procedures for an object will be together.
uspPersonInsert
uspPersonDelete
uspPersonGet
etc...
Again, this does not really matter what action words that you use, but this will be helpful to classify
the behavior characteristics.
Naming Stored Procedure Object
The last part of this is the object that you are working with. Some of these may be real objects like
tables, but others may be business processes. Keep the names simple, but meaningful. As your
database grows and you add more and more objects you will be glad that you created some standards.
Schema Names
Another thing to consider is the schema that you will use when saving the objects. A schema is the a
collection of objects, so basically just a container. This is useful if you want to keep all utility like
objects together or have some objects that are HR related, etc...
This logical grouping will help you differentiate the objects further and allow you to focus on a group
of objects.
HR.uspGetPerson
HR.uspInsertPerson
UTIL.uspGet
UTIL.uspGetLastBackupDate
etc...
To create a new schema you use the CREATE SCHEMA command
Here is a simple example to create a new schema called "HR" and giving authorization to this schema
to "DBO".
Schema
Prefix
Action
Object
Take the time to think through what makes the most sense and try to stick to your conventions.
Explanation
As mentioned above there is not really any reason to return messages about what is occuring within
SQL Server when you run a stored procedure. If you are running things from a query window, this
may be useful, but most end users that run stored procedures through an application would never see
these messages.
You can still use @@ROWCOUNT to get the number of rows impacted by a SQL statement, so
turning SET NOCOUNT ON will not change that behavior.
23
Explanation
The syntax is very straightforward to drop a stored procedure, here are some examples.
Explanation
Modifying or ALTERing a stored procedure is pretty simple. Once a stored procedure has been
created it is stored within one of the system tables in the database that is was created in. When you
modify a stored procedure the entry that was originally made in the system table is replaced by this
new code. Also, SQL Server will recompile the stored procedure the next time it is run, so your users
are using the new logic. The command to modify an existing stored procedure is ALTER
PROCEDURE or ALTER PROC.