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

CSE1012Y Database Systems Labsheet 13 - Stored Procedures: Create A Stored Procedure

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

CSE1012Y Database Systems

Labsheet 13 – Stored Procedures

Create a Stored Procedure

A stored procedure is a group of SQL statements compiled into a single execution plan. Stored
procedures are similar to procedures in other programming languages in that they can:
 Accept input parameters and return multiple values in the form of output parameters to
the calling procedure or batch.
 Contain programming statements that perform operations in the database, including
calling other procedures.
 Return a status value to a calling procedure or batch to indicate success or failure (and the
reason for failure).

A stored procedure is nothing more than prepared SQL code that can be saved and used over and
over again.  So, if there is a query that has to be executed many times, instead of having to write
the query over and over again, it can be saved as a stored procedure and then called whenever the
query needs to be executed.

In addition to running the same SQL code over and over again, there is also 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.

The CREATE PROCEDURE statement is used to create a permanent procedure in the current
database as follows:

CREATE PROCEDURE sp_procedurename @par1 DATATYPE


, @par2 DATATYPE
, @par3 DATATYPE OUTPUT
, ...
AS
BEGIN
DECLARE @var1 DATATYPE, @var2 DATATYPE, …
statements

...
END

After a procedure has been created, it will appear in the Object Explorer. (You sometimes need
to refresh the window).

1
Creating a simple stored procedure  

(CREATE PROCEDURE)

In this example we will look at creating a simple stored procedure. We will use the following
Address table:

Address table

Column Data type Nullability Description


AddressID int Not null Primary key for address rows.
AddressLine1 varchar(60) Not null First street-address line.
AddressLine2 varchar(60) Null Second street address line.
City varchar(30) Not null Name of the city.
StateProvinceID int Not null Unique identification number for the state or province.
PostalCode varchar(15) Not null Postal code for the street address.

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 Address table.

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

SELECT * FROM Address

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

CREATE PROCEDURE spGetAddress


AS
SELECT * FROM Address
GO

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

EXEC spGetAddress

The EXECUTE or (EXEC) command is used to execute a stored procedure.

2
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 cannot 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.

Create a Stored Procedure 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 section we will look at passing
parameter values to a stored procedure.

Explanation
Just like you have the ability to use parameters with your SQL code you can also setup your
stored procedures to except one or more parameter values.

One Parameter

In this example we will query the Address table below, 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.

CREATE PROCEDURE spGetAddress @City varchar(30)


AS
SELECT *
FROM Address
WHERE City = @City
GO

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

EXEC spGetAddress @City = 'New York'

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.

3
CREATE PROCEDURE spGetAddress @City varchar(30)
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 you will get an
error message such as the following:

Msg 201, Level 16, State 4, Procedure spGetAddress, Line 0

Procedure or function 'spGetAddress' expects parameter '@City', which was not


supplied.

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.

CREATE PROCEDURE spGetAddress @City varchar(30) = NULL


AS
SELECT *
FROM Address
WHERE City = @City
GO

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. (Note: if the City column has NULL values this will not include these values.
You will have to add additional logic for City IS NULL)

CREATE PROCEDURE spGetAddress @City varchar(30) = NULL


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

4
Multiple Parameters

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.

CREATE PROCEDURE spGetAddress @City varchar(30) = NULL, @AddressLine1


varchar(60) = 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 spGetAddress @City = 'Calgary'


--or
EXEC spGetAddress @City = 'Calgary', @AddressLine1 = 'A'
--or
EXEC spGetAddress @AddressLine1 = 'Acardia'
-- etc...

Returning stored procedure parameter values to a calling stored procedure   


(OUTPUT)

Overview
In a previous section 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.

Explanation
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".

Simple Output

CREATE PROCEDURE spGetAddressCount @City varchar(30), @AddressCount int


OUTPUT
AS
SELECT @AddressCount = count(*)
FROM Address

5
WHERE City = @City

Or it can be done this way:

CREATE PROCEDURE spGetAddressCount @City varchar(30), @AddressCount int OUT


AS
SELECT @AddressCount = count(*)
FROM Address
WHERE City = @City

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 spGetAddressCount @City = 'Calgary', @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 spGetAddressCount 'Calgary', @AddressCount OUTPUT
SELECT @AddressCount

Classwork
Create a stored procedure, sp_add_num, which performs the sum of two numbers.

6
Modifying an existing SQL Server stored procedure   

(ALTER PROCEDURE)

Overview
When you first create your stored procedures it may work as planned, but how to do you modify
an existing stored procedure.  In this sectionwe look at the ALTER PROCEDURE command and
it is used.

Explanation
Modifying or ALTERing a stored procedure is pretty simple.  Once a stored procedure has been
created it is stored within one of the system tables in the database that is was created in.  When
you modify a stored procedure the entry that was originally made in the system table is replaced
by this new code.  Also, SQL Server will recompile the stored procedure the next time it is run,
so your users are using the new logic.  The command to modify an existing stored procedure is
ALTER PROCEDURE or ALTER PROC.

Modifying an Existing Stored Procedure

Let's say we have the following existing stored procedure:  This allows us to do an exact match
on the City.

CREATE PROCEDURE spGetAddress @City varchar(30)


AS
SELECT *
FROM Address
WHERE City = @City
GO

Let's say we want to change this to do a LIKE instead of an equals.

To change the stored procedure and save the updated code you would use the ALTER
PROCEDURE command as follows.

ALTER PROCEDURE uspGetAddress @City nvarchar(30)


AS
SELECT *
FROM Address
WHERE City LIKE @City + '%'
GO

Now the next time that the stored procedure is called by an end user it will use this new logic.

7
Deleting a SQL Server stored procedure  

(DROP PROCEDURE)

Overview
In addition to creating stored procedures there is also the need to delete stored procedures.  This
topic shows you how you can delete stored procedures that are no longer needed.

Explanation
The syntax is very straightforward to drop a stored procedure, here are some examples.

Dropping Single Stored Procedure

To drop a single stored procedure you use the DROP PROCEDURE or DROP PROC command
as follows.

DROP PROCEDURE spGetAddress


GO
-- or
DROP PROC spGetAddress
GO
-- or
DROP PROC dbo.spGetAddress -- also specify the schema

Dropping Multiple Stored Procedures

To drop multiple stored procedures with one command you specify each procedure separated by
a comma as shown below.

DROP PROCEDURE spGetAddress, spInsertAddress, spDeleteAddress


GO
-- or
DROP PROC spGetAddress, spInsertAddress, spDeleteAddress
GO

Using comments in a SQL Server stored procedure  

8
Overview
One very helpful thing to do with your stored procedures is to add comments to your code.  This
helps you to know what was done and why for future reference, but also helps other DBAs or
developers that may need to make modifications to the code.

Explanation
SQL Server offers two types of comments in a stored procedure; line comments and block
comments.   The following examples show you how to add comments using both techniques. 
Comments are displayed in green in a SQL Server query window.

Line Comments

To create line comments you just use two dashes "--" in front of the code you want to comment.  
You can comment out one or multiple lines with this technique.

In this example the entire line is commented out.

-- this procedure gets a list of addresses based


-- on the city value that is passed
CREATE PROCEDURE spGetAddress @City varchar(30)
AS
SELECT *
FROM Address
WHERE City = @City
GO

This next example shows you how to put the comment on the same line.

-- this procedure gets a list of addresses based on the city value that is
passed
CREATE PROCEDURE spGetAddress @City varchar(30)
AS
SELECT *
FROM Address
WHERE City = @City -- the @City parameter value will narrow the search
criteria
GO

Block Comments

9
To create block comments the block is started with "/*" and ends with "*/".   Anything within
that block will be a comment section.

/*
-this procedure gets a list of addresses based
on the city value that is passed
-this procedure is used by the HR system
*/
CREATE PROCEDURE upGetAddress @City varchar(30)
AS
SELECT *
FROM Address
WHERE City = @City
GO

Combining Line and Block Comments

You can also use both types of comments within a stored procedure.

/*
-this procedure gets a list of addresses based
on the city value that is passed
-this procedure is used by the HR system
*/
CREATE PROCEDURE spGetAddress @City varchar(30)
AS
SELECT *
FROM Address
WHERE City = @City -- the @City parameter value will narrow the search
criteria
GO

Using Control Statements in a SQL Server stored procedure   

10
IF...ELSE Statement

The IF...ELSE statement imposes conditions on the execution of a statement. The statement that
follows an IF keyword and its condition is executed if the condition is satisfied: the Boolean
expression returns TRUE. The optional ELSE keyword introduces another statement that is
executed when the IF condition is not satisfied: the Boolean expression returns FALSE.

The IF...ELSE statement is used as follows:

IF Boolean-expression
[BEGIN]
statements
[END]
[ELSE
[BEGIN]
statements
[END]]

Classwork
Create a stored procedure, sp_add_num_if, which performs the sum of two numbers. If
the sum exceeds 10, an appropriate message is printed, else a different message is printed.

WHILE loop

The WHILE loop sets a condition for the repeated execution of a statement block. The
statements are executed repeatedly as long as the specified condition is true. The execution of
statements in the WHILE loop can be controlled from inside the loop with the BREAK and
CONTINUE keywords.
The WHILE loop is used as follows:

WHILE Boolean-expression
statement-block
[BREAK/CONTINUE]

BREAK: causes an exit from the innermost WHILE loop. Any statements that appear after the
END keyword, marking the end of the loop, are executed.
CONTINUE: causes the WHILE loop to restart, ignoring any statements after the CONTINUE
keyword.

Classwork
CREATE a strored procedure sp_add_num_while which adds a number to itself until a
threshold is reached. The procedure should print the final sum.
Exercises

1. Write a stored procedure, sp_math_op, which takes 3 parameters, the first 2 being two integer

11
values and the 3rd one a letter indicating a mathematical operation ('A' for addition, 'S' for
subtraction, 'M' for multiplication and 'D' for division). The procedure should return the
result of the specified operation on the 2 numbers.

2. Write procedures sp_f2c and sp_c2f, which convert between Centigrade and Fahrenheit
scales. (Hint: 5(F-32) = 9C)
Note:
sp_f2c: takes a Fahrenheit value and converts to Centigrade
sp_c2f: takes a Centigrade value and converts to Fahrenheit

3. Write a procedure, sp_convert, which combines the above two procedures. For example,
calling procedure sp_convert with parameters 'C' and a value, will convert the value to
Fahrenheit and calling procedure sp_convert with parameters 'F' and a value, will convert the
value to Centigrade. (Note that you can include an EXECUTE command in your stored
procedure).

4. Write a procedure, sp_perimeter, which computes the perimeter of different forms. Form
can be of:
{square, side}
{circle, Radius}
{triangle, A, B, C}

5. Write a procedure, sp_vat, to calculate the final price of an item after applying Value
Added Tax (VAT). The function will take as arguments the type of the item and the price
before application of VAT. Items of type ‘Medicine’ and ‘Baby Food’ are exempt of VAT. A
VAT of 10% is applied to items of type ‘Food’ and ‘Clothing’ and a VAT of 15% is applied to
all other item types.

6. Write a procedure, sp_sum_all, that returns the sum of the squares of all numbers between
two integer values provided by the user, inclusive.
For example, if sp_sumAll is executed with parameters 2 and 5, the result should be 54, i.e.
22 + 32 + 42 + 52.

7. Use basic loop to write a procedure, sp_square_integer_loop, which squares an integer


until it reaches a value higher than 1000. For example, with parameter 3, the procedure
should return 6561.

12

You might also like