Try an online SQL class for free!
Additional Resources

Stored Procedures

In this lesson of the SQL tutorial, you will learn...
  1. The purpose of stored procedures.
  2. To create and call stored procedures.
  3. To use stored procedures.
  4. To drop stored procedures.

Stored procedures are essentially functions that you can create in the database and reuse. What's neat about them from a usability standpoint is that they can take input parameters and then return a result.

Creating Stored Procedures

Stored procedures are created with the CREATE PROCEDURE statement. The syntax is shown below.

Syntax
CREATE PROCEDURE procedure_name
@param data_type = default_value,
@param data_type = default_value,
@param data_type = default_value
AS
-- statements for procedure here

The demo below shows a script that creates a simplified version of a SalesByCategory stored procedure that ships with SQL Server 2000's Northwind sample database.

Code Sample: StoredProcedures/Demos/StoredProc.sql

CREATE PROCEDURE SalesByCategory
 @CategoryName nvarchar(15),
 @OrdYear int = 1998
AS

SELECT ProductName, SUM(OD.Quantity * (1-OD.Discount) * OD.UnitPrice) AS TotalPurchase
FROM "Order Details" od, Orders o, Products p, Categories c
WHERE od.OrderID = o.OrderID
 AND od.ProductID = p.ProductID
 AND p.CategoryID = c.CategoryID
 AND c.CategoryName = @CategoryName
 AND DATEPART(year,OrderDate) = @OrdYear
GROUP BY ProductName
ORDER BY ProductName

--Call stored procedure
EXEC SalesByCategory 'Seafood', 1997
Code Explanation

The procedure has two parameters defined @CategoryName, which is required, and @OrdYear, which has a default value of 1998.

The stored procedure can be called with the EXEC command:

EXEC SalesByCategory 'Seafood', 1997.

The stored procedure shown in the previous demo returns a result set; however, stored procedures can also be used to insert, update, or delete data. Using conditional processing, it is possible to check parameters to make sure the input parameters are valid. It is also possible to run multiple queries and return multiple results with a single stored procedure. That advanced material is beyond the scope of this course. But even the simple stored procedure shown here is valuable as it makes it easy to get a sales report for a specific category of goods without writing a full SELECT query.

Dropping Stored Procedures

Dropping stored procedures is easy enough:

Syntax
DROP PROCEDURE stored_procedure_name

Exercise: Creating a Stored Procedure

Duration: 20 to 30 minutes.

In this exercise you will create a stored procedure that returns a sales report for a given time period for a given employee.

  1. Open a new query window and create a spSalesReport stored procedure that returns first name, last name, number of orders (NumOrders) and revenue for a given employee for a given time period. The stored procedure should take four required input parameters:
    1. @StartOrderDate
    2. @EndOrderDate
    3. @SpFirstName
    4. @SpLastName
  2. Test the stored procedure by running:
    EXEC spSalesReport '11/1/1997','12/1/1997', 'Steven', 'Buchanan'

Create a second stored procedure called spSalesReport2 that is the same except that the @SpFirstName and @SpLastName parameters default to empty strings. When called like:

EXEC spSalesReport2 '11/1/1997','12/1/1997', 'Steve'

... it should return the results for Steven Buchanan.

When called with no parameters, it should return result for all the salespeople.

Benefits of Stored Procedures

Stored procedures have many benefits, including:

  • Speed - Stored procedures are pre-compiled, so the execution plan doesn't have to be figured out each time they're called. This can result in a significant performance improvement.
  • Code reuse and abstraction - Stored procedures often involve complex code. It's nice that this code doesn't have to be rewritten over and over again and that even entry-level SQL programmers can make use of it with a simple stored procedure call.
  • Security - Permissions can be granted for stored procedures while being restricted for the underlying tables. This allows the DBA to provide a method for SQL programmers and report writers to access and/or manipulate data in a safe way.
  • Reduced traffic between client and server - Since the bulk of the query is already stored on the server and only the relatively short stored procedure call has to get sent, traffic to the server is decreased.

Stored Procedures Conclusion

In this lesson of the SQL tutorial, you learned the purpose and benefits of stored procedures and how to create, use and drop them.

To continue to learn SQL go to the top of this page and click on the next lesson in this SQL Tutorial's Table of Contents.
Last updated on 2009-05-11

Use of http://www.learn-sql-tutorial.com (Website) implies agreement to the following:

Copyright Information

All pages and graphics on Website are the property of Webucator, Inc. unless otherwise specified.

None of the content on Website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of pages or content on Website

This content may not be printed or saved. It is for online use only.


Linking to Website

You may link to any of the pages on Website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

Website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).


For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm