Monday, 31 March 2014

Creating a simple 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 would be as follows which will return all rows from this table.
SELECT * FROM AdventureWorks.Person.Address

To create a stored procedure to do this the code would look like this:
CREATE PROCEDURE uspGetAddress
AS
SELECT * FROM AdventureWorks.Person.Address
GO

To call the procedure to return the contents from the table specified, the code would be:
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.
On 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.

SQL Server Query Execution Plans for beginners – Clustered Index Operators

In this article we will continue discussing the various execution plan operators related to clustered indexes and what they do, when do the...