Home > Guides > Databases > SQL Server

Toggle Open Guide Table of ContentsGuide Contents

Close Table of ContentsGuide Contents

Close Table of Contents

Database Objects: Stored Procedures

Last updated Jan 1, 2004.

We've been learning about various objects stored in SQL Server 2000 databases. The two main categories of these objects are things that store data and things that access or provide access to data. We've already talked about all of the objects that fit the first category - tables. That's right; tables are the only objects that actually store data!

All the other objects we're studying belong in the second category: things that access or provide access to data. We've already learned about one of those objects – the view. As we learned in that tutorial, a view is really just a text-object in the database. A view stores select statements that provide a "window" into a table or collection of tables. We learned that views can slice the data down columns, restrict the data returned to a few rows, hide the complexity of the select statements, and simplify security. In the tutorial on views, I explained a few limitations that views have, and I told you that I'd demonstrate how to get around those limitations with stored procedures. So as promised, here you are!

Stored procedures are similar to views. They are just text objects, and don't store any data. They do provide access to data. They can return datasets, just like a view, but that's where the similarity ends.

A stored procedure goes farther than a simple select statement. Stored procedures can have full-blown code, meaning that they can have loops, conditions, and other program logic. They also have a serious trump-card over a view – they can accept inputs and return outputs. The output they produce can be a recordset, and they can also return a computed value, the result of a calculation on values returned from another stored procedure, and more. I'll show you a simple input and output in a bit.

Need more? How about being able to send the status of the stored procedure indicating the success of the procedure, and even the reason for the failure!

Another big advantage with stored procedures is that they provide that "ownership chain" I described for views. That means that as long as the same owner creates all the referenced objects, you only have to grant rights on the stored procedure. You don't have to spend lots of time mucking about with rights on the individual tables, views and what-not.

Finally, stored procedures are speedy. When a stored procedure is run for the first time, SQL Server does quite a few things. The SQL Server Query Optimizer creates an execution plan for the stored procedure, and then the stored procedure is pre-compiled, and some of the data might even be cached. Any calls to that stored procedure after that are a "free ride" – well, sort of. Even if the subsequent calls aren't completely free, they are pretty quick after the first call.

So now that you're all excited about the advantages to stored procedures, let's take a look at how to create them. To create views, you'll use a simple CREATE statement, to delete them a DROP statement, and to change one, the ALTER statement. Which brings up an interesting aside...

NOTE

You may wonder why you should use the ALTER statement when changing a view or stored procedure. After all, the ALTER statement looks just like the CREATE statement. Why not just drop the object and re-create it? Less syntax to worry about!

Well, the answer has to do with security. If you drop an object, the database forgets all about it. Everything is forgotten, including the owner and who had access to it, and what kind of access that was. If you use the ALTER command, all that is kept intact. That can be kind of important if you have an elaborate security setup!

I'll start off by showing you how to create a basic stored procedure. As always, we'll use the pubs database in SQL Server to perform our tests. Here's a simple stored procedure that returns the first and last names of the authors in the authors table:

CREATE PROCEDURE usp_Test AS
SELECT au_fname, au_lname
FROM authors
ORDER BY au_lname

Hey, did you see that? It's right there in the last line. When we created a view, one of the limitations was that the view couldn't have an ORDER BY clause in it. Yet another advantage to stored procedures!

OK, that's how you make one – how do you run it? Simple! Here's a sample of that:

EXEC usp_Test

Okay, a couple of things are important here. The first is that when I created the stored procedure, I started the name with usp_. You don't really have to do that; some "professional" developers cringe when I do. The reason I do it has to do with two things. The first reason is that it's how I was taught (old habits die hard!).

The second, mnore logical reason is that when you're in a big shop, it's important to be able to quickly locate objects in a database. The usp_ stands for User Stored Procedure. In a text list of objects, it's clear what it is. Why not use just sp_, for Stored Procedure? Because Microsoft took that one already! You see, there are several stored procedures already in the master database. You may have already seen a few in my discussions on tracing.

So we've got a simple stored procedure that when run returns a recordset. Next, let's look at a stored procedure that accepts input.

First, I'll get rid of the stored procedure I made a minute ago:

DROP PROCEDURE usp_Test

And now I'll create one that accepts input:

CREATE PROCEDURE usp_Test @lname varchar(30) AS
SELECT au_fname, au_lname
FROM authors
WHERE au_lname = @lname
ORDER BY au_lname

What's happening here is that the stored procedure takes a variable amount of characters up to 30 (varchar(30)) as an input and compares that string to the au_lname field. Let's run it:

EXEC usp_Test 'White'

And there you have it. You can see I've supplied the parameter there at the end, in single-quotes. You may wonder if you can have more than one parameter. The answer is yes, you can have lots of them. If you can remember the order you wrote them in the stored procedure, you can just supply the variables when you run the stored procedure in order, with the variables separated by commas. A better solution is to supply the name of the parameter right in the call, like this:

EXEC usp_Test @lname = 'White', @nextvariable = 'nextstring', ...

You may have also noticed that I'm placing EXEC in front of the stored procedure name. You don't always have to do that. You can just type usp_Test 'White' and the stored procedure will run. It won't run, however, if the stored procedure isn't the first item in the list of things you're running at one time, called a "batch". Here's an example:

-- will run
usp_Test 'White'
GO
--won't run:
SELECT * FROM authors
usp_Test 'White'
GO

See the difference? The safer bet is to always preface the stored procedure with EXEC.

The stored procedures we've made so far provide output in the form of recordsets. What if you're after something else? Perhaps a numeric value? Here's how you can accomplish that, a little useless stored procedure that performs a row count from the authors table:

CREATE PROCEDURE usp_Test (@RowCount int OUTPUT )
AS
SELECT @RowCount = Count(*)
FROM authors

The only thing new here is the OUTPUT parameter. But using it does get a little more complicated. To access the results, we'll have to do a few things first.

You see, this stored procedure returns a value, but it stores the value in memory. Nothing actually reports to the screen with this type of output, since this stored procedure is used more with a programming application in mind.

To get at the return value, the first thing we need to do is carve out some memory space to hold the result, using the DECLARE statement:

DECLARE @GetCount INT

Now we have a little bit of space up in memory to hold the results of something.

Next, we need to run the stored procedure, and return the output variable, storing it in the one we just created:

EXEC usp_Test @RowCount = @GetCount OUTPUT

Finally, we can take a look at the results:

SELECT @GetCount

And there you have it. It really isn't that difficult when you break it all down.

OK, I think that's enough for now. We'll get into more advanced stored procedure mechanics as we progress through our tutorials. Hopefully this little introduction will get you started experimenting with your own stored procedures. I also have several excellent sites on stored procedures in the references section of this InformIT area to help you along the way. Happy coding!

InformIT Articles and Sample Chapters

Stored Procedures - Sams Teach Yourself SQL Server 7 in 24 Hours, By Matt Shepker. Published by Sams. OCT 19, 1999.

The Guru's Guide to Transact-SQL By Ken Henderson. Published by Addison Wesley Professional. FEB 23, 2000.

Online Resources

Alexander Chigrik examines SQL Server Stored Procedures Administration, including Performance, security and reliability.

Learn how to create and manage SQL Server Stored Procedures using Transact-SQL.

SQL Server Stored Procedures 101.

Optimizing SQL Server Stored Procedures to Avoid Recompiles. by Randy Dyess.

Microsoft SQL Server - Stored Procedures: Returning Data.

Increase SQL Server stored procedure performance with these tips.

ASP 101 - SQL Server Stored Procedures Sample.

DevASP.Net SQL Server Stored Procedures Articles and Samples can be found here.

Discussions

Keeping my DBA Job
Posted Feb 20, 2008 04:10 AM by Scarpetta
0 Replies
Database Objects: Triggers
Posted Jan 18, 2008 06:36 AM by durao
1 Replies
The dot is not working
Posted Dec 2, 2007 08:22 AM by eliassal
0 Replies

Make a New Comment

You must log in in order to post a comment.

Related Resources

Buck WoodyIf it's Free it's for Me
By Buck WoodyJanuary 26, 2009 No Comments

Sign me up for anything free these days. I just ran across a book that promises to help you build a web site for free...

Buck WoodyNot stressing about the job
By Buck WoodyJanuary 10, 20094 Comments

You know, I think that the media shares a HUGE part of the blame for the economy. They screamed "things look bad!" so much that the general public got spooked and quit spending, thinking the worst. That leads to a spiral where people don't buy what you sell, and things DO get bad.  

Buck WoodyCost Cutting and the DBA
By Buck WoodyDecember 19, 20083 Comments

It seems all the news can talk about is the "bad economy". Personally, I think they have talked a lot of people into panic mode, which has in fact made any kind of slowdown even worse. But hey, whatever sells TV ad time, right?

So since the public has so heartily embraced the news' view of the world, business has in fact slowed down. And it seems that the business wants everyone to cut costs. So what can the DBA do?

See More Blogs

Informit Network