- Introduction
- Table of Contents
- Microsoft SQL Server Defined
- Microsoft SQL Server Features
- Microsoft SQL Server Administration New
- Microsoft SQL Server Programming
- An Outline for Development
- Database
- Database Services
- Database Objects: Databases
- Database Objects: Tables
- Database Objects: Table Relationships
- Database Objects: Keys
- Database Objects: Constraints
- Database Objects: Data Types
- Database Objects: Views
- Database Objects: Stored Procedures
- Database Objects: Indexes
- Database Objects: User Defined Functions
- Database Objects: Triggers
- Database Design: Requirements, Entities, and Attributes
- Database Design: Finalizing Requirements and Defining Relationships
- Database Objects: Entity Relationship Diagrams
- Database Design: The Logical ERD
- Database Design: Adjusting The Model
- Database Design: Normalizing the Model
- Database Design: Creating The Physical Model
- Database Design: Changing Attributes to Columns
- Database Design: Creating The Physical Database
- NULLs
- The SQL Server Sample Databases
- The SQL Server Sample Databases - pubs
- The SQL Server Sample Databases - NorthWind
- The SQL Server Sample Databases - Adventureworks
- The SQL Server Sample Databases - Adventureworks Derivatives
- UniversalDB: The Demo and Testing Database, Part 1
- UniversalDB: The Demo and Testing Database, Part 2
- UniversalDB: The Demo and Testing Database, Part 3
- UniversalDB: The Demo and Testing Database, Part 4
- Getting Started with Transact-SQL
- Transact-SQL: Limiting Results
- Transact-SQL: More Operators
- Transact-SQL: Ordering and Aggregating Data
- Transact-SQL: Subqueries
- Transact-SQL: Joins
- Transact-SQL: Complex Joins - Building a View with Multiple JOINs
- Transact-SQL: Inserts, Updates, and Deletes
- An Introduction to the CLR in SQL Server 2005
- Design Elements Part 1: Code Format and Comments
- Design Elements Part 2: Controlling SQL's Scope
- Design Elements Part 3: Error Handling
- Design Elements Part 4: Variables
- Design Elements Part 5: Where Does The Code Live?
- Design Elements Part 6: Math Operators and Functions
- Design Elements Part 7: Statistical Functions
- Design Elements Part 8: Summarization Statistical Algorithms
- Design Elements Part 9:Representing Data with Statistical Algorithms
- Design Elements Part 10: Interpreting the Data—Regression
- Design Elements Part 11: String Manipulation New
- Design Elements Part 12: Loops
- Design Elements Part 13: Recursion
- Design Elements Part 14: Arrays
- Design Elements Part 15: Event-Driven Programming Vs. Scheduled Processes
- Design Elements Part 16: Event-Driven Programming
- Design Elements Part 17: Program Flow
- Forming Queries Part 1: Design
- Forming Queries Part 2: Query Basics
- Forming Queries Part 3: Query Optimization
- Forming Queries Part 4: SET Options
- Forming Queries Part 5: Table Optimization Hints
- Using SQL Server Templates
- Transact-SQL Unit Testing
- Index Tuning Wizard
- Unicode and SQL Server
- SQL Server Development Tools
- Performance Tuning
- Practical Applications
- Professional Development
- Business Intelligence
- Tips and Troubleshooting
- Additional Resources
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.


Account Sign In
View your cart