1 Aug 2024

Creating a simple SQL Server stored procedure

 

Overview

As mentioned in the tutorial overview a stored procedure is nothing more than stored SQL code that you would like to use over and over again.  In this example we will look at creating a simple stored procedure.

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.

SELECT * FROM Person.Address

To create a stored procedure to do this the code would look like this:

USE AdventureWorks
GO

CREATE PROCEDURE dbo.uspGetAddress
AS
SELECT * FROM Person.Address
GO

To call the procedure to return the contents from the table specified, the code would be:

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.

2 comments:

SQL Server Copilot AI

 Here are some of the latest tips and advanced concepts for Microsoft SQL Server (MS SQL) in 2024: 1. SQL Server Copilot AI Microsoft has in...