Creating a simple SQL Server stored procedure


By:
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.






Comments For This Article




Thursday, July 23, 2020 - 1:54:35 PM - Tamiru Simegn Alemu Back To Top (86182)

This is a wonderful explanation that I understand. Thank you so much.


Thursday, February 6, 2020 - 9:37:00 AM - David Fisher Back To Top (84214)

We appreciate example code that actually works as described. Thanks!


Thursday, January 4, 2018 - 4:37:42 AM - asna Back To Top (74749)

very helpful & interesting..thank you.


Wednesday, September 13, 2017 - 5:30:17 AM - SANDEEP KUMAR Back To Top (66230)

 

 

its very helpful for all of us..Thank's


Monday, September 4, 2017 - 6:26:11 AM - Zia Sheikh Back To Top (65826)

Thanks Greg Robidoux!!! These tutorials are very helpful, keep it up.


Thursday, August 17, 2017 - 10:07:47 AM - sivakumar.sivaraj Back To Top (64966)

 very helpfull.


Monday, January 30, 2017 - 5:30:16 AM - niwar Back To Top (45725)

thank you


Tuesday, October 11, 2016 - 7:48:35 AM - Vrushali Wagh Back To Top (43536)

Very Helpful & simple to understand.


Saturday, June 4, 2016 - 1:15:02 AM - Yogesh Pandey Back To Top (41609)

VERY HELPFULL 


Tuesday, February 2, 2016 - 1:42:14 AM - bhavsinh Back To Top (40568)

how to put validation in user insert data in databse

 















get free sql tips
agree to terms