Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views6 pages

Tutorial_StoredProcedures

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 6

Lecturer : Damien Kettle Database Administration

Tutorial – Stored Procedures

Overview
A stored procedure is nothing more than prepared SQL code that you save so you can reuse the code
over and over again. So if you think about a query that you write over and over again, instead of
having to write that query each time you would save it as a stored procedure and then just call the
stored procedure to execute the SQL code that you saved as part of the stored procedure.

In addition to running the same SQL code over and over again you also have the ability to pass
parameters to the stored procedure, so depending on what the need is the stored procedure can act
accordingly based on the parameter values that were passed.

Creating a Simple Stored Procedure


Before you create a stored procedure you need to know what your end result is, whether you are
selecting data, inserting data, etc..

Use below DDL Statement to create the Address table on your database:

CREATE TABLE dbo.Address


( AddressId int IDENTITY(1,1) NOT NULL,
AddressLine1 varchar(50) NOT NULL,
AddressLine2 varchar(50) NOT NULL,
AddressLine3 varchar(50) NULL,
City varchar(20) NOT NULL,
Country varchar(20) NOT NULL,
CONSTRAINT PK_Address PRIMARY KEY CLUSTERED (AddressId))

Use below Insert Statement to Insert some data:

INSERT INTO dbo.Address


(AddressLine1, AddressLine2, AddressLine3, City, Country)
VALUES
('Grand Canal Street', 'D4', NULL, 'Dublin', 'Ireland'),
('Carvery Lane', 'D6', NULL, 'Dublin', 'Ireland'),
('Pimlico', 'D8', NULL, 'Dublin', 'Ireland'),
('Cork Street', 'D8', NULL, 'Dublin', 'Ireland'),
('Upper Rathmines Road', 'D6', NULL, 'Dublin', 'Ireland'),
('Newtwon Buildings', 'Newtown', NULL, 'Waterford', 'Ireland'),
('Hill of Tara', 'Tara', NULL, 'Meath', 'Ireland')
Lecturer : Damien Kettle Database Administration

In this simple example we will just select all data from the Address table that is stored in your
Student Database.

So the simple T-SQL code would be as follows which will return all rows from this table:

SELECT * FROM dbo.Address

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

CREATE PROCEDURE uspGetAddress


AS
SELECT * FROM dbo.Address
GO

(NOTE: The GO command isn't a Transact-SQL statement, but a special command recognized by
several MS utilities including SQL Server Management Studio code editor.
The GO command is used to group SQL commands into batches which are sent to the server
together.)

You should now see your Stored Procedure in the Stored Procedures folder under Programmability.

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.
Lecturer : Damien Kettle Database Administration

Creating Stored Procedures With Parameters


The real power of stored procedures is the ability to pass parameters and have the stored procedure
handle the differing requests that are made. In this topic we will look at passing parameter values to
a stored procedure.

In this example we will query the Address table but instead of getting back all records we will limit it
to just a particular city. This example assumes there will be an exact match on the City value that is
passed.

We will now ALTER the Stored Procedure uspGetAddress to accept an input parameter as per below:

ALTER PROCEDURE uspGetAddress


@City varchar(20)
AS
SELECT *
FROM Address
WHERE City = @City
GO

To call this stored procedure we would execute it as follows:

EXEC uspGetAddress @City = 'Waterford'

You should get back below result:

We can also do the same thing, but allow the users to give us a starting point to search the data.
Here we can change the "=" to a LIKE and use the "%" wildcard.

ALTER PROCEDURE uspGetAddress


@City varchar(20)
AS
SELECT *
FROM Address
WHERE City LIKE @City + '%'
GO

In both of the proceeding examples it assumes that a parameter value will always be passed. If you
try to execute the procedure without passing a parameter value as per below:

EXEC uspGetAddress

you will get an error message such as the following:


Msg 201, Level 16, State 4, Procedure uspGetAddress, Line 0
Procedure or function 'uspGetAddress' expects parameter '@City', which was not supplied.
Lecturer : Damien Kettle Database Administration

Default Parameter Values


In most cases it is always a good practice to pass in all parameter values, but sometimes it is not
possible. So in this example we use the NULL option to allow you to not pass in a parameter value.
If we create and run this stored procedure as is it will not return any data, because it is looking for
any City values that equal NULL.

ALTER PROCEDURE uspGetAddress


@City varchar(20) = NULL
AS
SELECT *
FROM Address
WHERE City = @City
GO

If you now execute the Stored Procedure using below line:

exec uspGetAddress

You will get no records returned because no City = NULL:

We could change this stored procedure and use the ISNULL function to get around this. So if a value
is passed it will use the value to narrow the result set and if a value is not passed it will return all
records.

ALTER PROCEDURE uspGetAddress


@City varchar(20) = NULL
AS
SELECT *
FROM Address
WHERE City = ISNULL(@City, City)
GO

If you now execute the Stored Procedure using below line:

exec uspGetAddress

You will get back below records:


Lecturer : Damien Kettle Database Administration

Multiple Paramaters
Setting up multiple parameters is very easy to do. You just need to list each parameter and the data
type separated by a comma as shown below.

ALTER PROCEDURE uspGetAddress


@City varchar(20) = NULL,
@AddressLine1 varchar(50) = NULL
AS
SELECT *
FROM Address
WHERE City = ISNULL(@City,City)
AND AddressLine1 LIKE '%' + ISNULL(@AddressLine1 ,AddressLine1) + '%'
GO

To execute this you could do any of the following:

EXEC uspGetAddress @City = 'Waterford'


--or
EXEC uspGetAddress @City = 'Waterford', @AddressLine1='New'
--or
EXEC uspGetAddress @AddressLine1='New'
Lecturer : Damien Kettle Database Administration

Returning Stored Procedure parameter values to a calling Stored


Procedure
Previously we discussed how to pass parameters into a stored procedure, but another option is to
pass parameter values back out from a stored procedure. One option for this may be that you call
another stored procedure that does not return any data, but returns parameter values to be used by
the calling stored procedure.

Setting up output parameters for a stored procedure is basically the same as setting up input
parameters, the only difference is that you use the OUTPUT clause after the parameter name to
specify that it should return a value. The output clause can be specified by either using the keyword
"OUTPUT" or just "OUT".

CREATE PROCEDURE uspGetAddressCount


@City varchar(20),
@AddressCount int OUTPUT
AS
SELECT @AddressCount = count(*)
FROM Address
WHERE City = @City
GO

Or it can be written like this:

CREATE PROCEDURE uspGetAddressCount


@City varchar(20),
@AddressCount int OUT
AS
SELECT @AddressCount = count(*)
FROM Address
WHERE City = @City
GO

To call this stored procedure we would execute it as follows. First we are going to declare a variable,
execute the stored procedure and then select the returned valued.

DECLARE @AddressCount int


EXEC uspGetAddressCount @City = 'Dublin', @AddressCount = @AddressCount
OUTPUT
SELECT @AddressCount

This can also be done as follows, where the stored procedure parameter names are not passed.

DECLARE @AddressCount int


EXEC uspGetAddressCount 'Dublin', @AddressCount OUTPUT
SELECT @AddressCount

You might also like