Professional Documents
Culture Documents
SQL Server Stored Procedures For Beginners
SQL Server Stored Procedures For Beginners
Do you want to view data in the database (SELECT), insert new records
(INSERT INTO), or do I want to change an existing record (UPDATE)?
With which tables will you have to work? Does it make sense to create a VIEW
first?
How often will this procedure actually be used?
Description
Created procedure
*/
Date
7/15/2003
Changed By
Tom ONeill
Of course, you can use your own name and todays date.
The next section will change only slightly. Every stored procedure needs the words CREATE
PROCEDURE followed by the name you want to assign to the stored procedure. While not
required, stored procedure names usually begin with the prefix usp_.
CREATE PROCEDURE usp_displayallusers
This tells the database that you are creating a stored procedure
usp_displayallusers. So far, your stored procedure should look like this:
named
/*
Name: usp_displayallusers
Description: displays all records and columns in USERLIST table
Author: Tom ONeill
Modification Log: Change
Description
Created procedure
*/
Date
7/15/2003
Changed By
Tom ONeill
Description
Created procedure
*/
Date
7/15/2003
Changed By
Tom ONeill
Input variables are essentially storage for data that you want to pass to your stored
procedure. Inside your stored procedure, you will declare variables at the top of the stored
procedure. How does the data get there? The data is entered in the exec statement that you
use to kick off the stored procedure. Well discuss that in more detail in a bit.
There are two types of variables that you can create in SQL Server stored procedures:
Global and Local. Since this is for beginners, I dont want to go crazy with too many options.
Well stick to local variables for now. You can name a variable most anything you want,
though it is best to stick with meaningful works and abbreviations. I also tend to avoid
punctuation, though underscores (_) are sometimes helpful. The only real requirement is
that you begin your variable with the @ symbol. Here are some examples:
@f_name
@fullname
@HomePhone
@ext
For every data element you want to pass, you will need to declare a variable. Declaring a
variable is quite easy. You decide on a name and a datatype (integer, text, etc.), and
indicate the name and datatype at the top of the procedure (below the CREATE
PROCEDURE line). Lets add a record to USERLIST. Remember the following:
usr_id is the primary key, and is system-generated. We wont need to pass a value
for it.
login, pswd, l_name, and email are required fields. We will have to pass
values for them.
First, lets create the header information (like the author, change log, etc.) that should be a
part of every stored procedure.
/*
Name: usp_adduser
Description: Adds a user
Author: Tom ONeill
Modification Log: Change
Description
Created procedure
*/
Date
7/15/2003
Changed By
Tom ONeill
Remember this?
CREATE PROCEDURE usp_adduser
/*
We will put the variables in here, later
*/
Add the CREATE PROCEDURE line, assigning the name usp_adduser. Our next step is to
remove the comments and declare our variables!
To start, lets look at how our variables will fit. We will need to create a variable for every
value we may need to pass. We may not pass a value to every field every time we run the
stored procedure. But, we do need to address the possibility that over the life of the stored
procedure, every data element may be used. The best way to address this issue is to create
a variable for every column in USERLIST. To keep this example simple, we are also
assuming that each of the columns can be NULL, and we will also be passing all of the
variables to the stored procedure. If some of the columns cannot be NULL, or if not all of
the columns will be affected, then the stored procedure and/or the exec statement have to
be rewritten slightly. The list below shows the variable and the field with which it is
associated.
@loginlogin
@pswdpswd
@f_namef_name
@l_namel_name
@address_1address_1
@address_2address_2
@citycity
@statestate
@zipcodezipcode
@emailemail
You have probably noticed that I gave the variables names that closely resemble the column
names with which they are associated. This will make it easier for you to maintain the
stored procedure in the future. Delete the comments about variables, and put your list of
variables beneath the CREATE PROCEDURE line.
CREATE PROCEDURE usp_adduser
@login
@pswd
@f_name
@l_name
@address_1
@address_2
@city
@state
@zipcode
@email
Next, add datatypes to each of the variables. The datatype assigned to the variable should
match the datatype assigned to the corresponding column in the database. For any
elements with the char, varchar, or numeric datatypes, you will need to put the
maximum character length list in parentheses after the datatype. Separate all variables
(except the last one), with a comma.
CREATE PROCEDURE usp_adduser
@login varchar(20),
@pswd varchar(20),
@f_name varchar(25),
@l_name varchar(35),
@address_1 varchar(30),
@address_2 varchar(30),
@city varchar(30),
@state char(2),
@zipcode char(10),
@email varchar(50)
With that last keystroke, you have created your first set of variables. To finish
usp_adduser, we will have to figure out what we want the stored procedure to do, then
add the appropriate code after the AS statement. This stored procedure will add a new
record to the USERLIST table, so we should use an INSERT statement. The SQL should be:
INSERT INTO USERLIST (login,
city, state, zipcode, email)
pswd,
f_name,
l_name,
address_1,
address_2,
The INSERT clause is pretty standard. The VALUES clause is a bit more complex. If you
have worked with databases, you are probably accustomed to seeing something like this:
VALUES (dnelson, dean2003, Dean, Nelson, 200 Berkeley Street, ,
Boston, MA, 02116, dnelson@test.com)
Since we are passing values from variables, it will look a bit different. Instead of putting the
actual values in the VALUES clause, well just put the variables. You wont need to use
quotes.
VALUES (@login, @pswd, @f_name, @l_name, @address_1, @address_2, @city,
@state, @zipcode, @email)
What does the entire stored procedure look like? Lets pull it all together.
/*
Name: usp_adduser
Description: Add new logins.
Author: Tom ONeill
Modification Log: Change
Description
Created procedure
*/
CREATE PROCEDURE usp_adduser
@login varchar(20),
@pswd varchar(20),
@f_name varchar(25),
@l_name varchar(35),
@address_1 varchar(30),
@address_2 varchar(30),
@city varchar(30),
@state char(2),
@zipcode char(10),
@email varchar(50)
Date
7/15/2003
Changed By
Tom ONeill
AS
INSERT INTO USERLIST (login, pswd, f_name, l_name, address_1, address_2,
city, state, zipcode, email)
VALUES (@login, @pswd, @f_name, @l_name, @address_1, @address_2, @city,
@state, @zipcode, @email)
It looks pretty long and complex, though we know from the process above that the stored
procedure is not necessarily complex; it just contains a lot of data. If you have been
working in a separate text editor, copy your stored procedure into the New Stored
Procedure window in SQL Server, and check the syntax. The result should be a successful
syntax check.
Now, we have a stored procedure that can accept external data. What do we do with it?
How do we get the data? Its not that hard; I promise. Well start with the exec statement
we used when we wrote our first stored procedure. Remember?
exec usp_displayallusers
We have a new stored procedure to execute, so this time, the command will be:
exec usp_adduser
There is still the issue of how to get our data into the stored procedure. Otherwise, all those
variables will be useless. To get data into our stored procedure, simply add the information
(in single quotes ) after the execute statement.
exec usp_adduser
Remember to pass as many parameters as you have variables, otherwise SQL Server will
throw an error. Since we have ten variables, your execute statement should look like this:
exec usp_adduser , , , , , , , , ,
Next, lets include the data that we will want to pass to usp_adduser. Your execute
statement will look like:
exec usp_adduser dnelson, dean2003, Dean, Nelson, 200 Berkeley
Street, , Boston, MA, 02116, dnelson@test.com
Running the query should be successful, and SQL Server will tell you that one row has been
affected. Now, lets try using input variables with some other query types.
Input Variables with SELECT and UPDATE Statements
Regardless of the type of SQL statement you use, variables work the same way. Look at the
following stored procedure:
/*
Name:
usp_updateuser
Date
7/15/2003
Changed By
Tom ONeill
login=dnelson
we have used:
login=@login
Remember, when you use variables, you do not have to use quotes.
The remaining SQL statement to address in this section is the SELECT statement. We can
pass data to a SELECT statement using variables as well. Ill let you do this one yourself.
Exercise: Pass Data to a SELECT Stored Procedure
Create a stored procedure that returns one record, based on the tables primary key.
Remember to:
Date
7/15/2003
Changed By
Tom ONeill
NOT NULL
) ON [PRIMARY]
GO
About the Author
Tom ONeill is a Senior Consultant in the Solutions/IDI practice at Deloitte & Touche. Toms
areas of expertise center web application development, database architecture, and
marketing automation. Tom ONeill can be reached at 617-437-2945 or at
tomoneill@deloitte.com.
Solutions/IDI, of Deloitte & Touche, is a technology consulting practice that provides various
technology and IT-related services worldwide.
Published with the express written permission of the author. Copyright