LISTING 28.11 Assigning a Default Value for a Parameter in a Stored Procedure ALTER PROCEDURE title_authors @state char2 = ‘%’ AS SELECT a.au_lname, a.au_fname, t.title FROM titles t INN
Trang 1Processing goes here
RETURN
If you want to help identify the data values for which the parameters are defined, it is
recommended that you give your parameters meaningful names Parameter names, like
local variables, can be up to 128 characters in length, including the @ sign, and they
must follow SQL Server rules for identifiers Up to 2,100 parameters can be defined for a
stored procedure
When you execute a procedure, you can pass the parameters by position or by name:
Passing parameters by position
EXEC myproc 1, 2, 3
Passing parameters by name
EXEC myproc @parm2 = 2, @parm2 = 1, @parm3 =3
Passing parameters by position and name
EXEC myproc 1, @parm3 =3, @parm2 = 2
After you specify one parameter by name, you must pass all subsequent parameters for the
procedure in that EXECUTE statement by name as well You cannot pass any of the
subse-quent parameters by position If you want to skip parameters that are not the last
parame-ter(s) in the procedure and have them take default values (as described in the next
section), you also need to pass parameters by name or use the DEFAULT keyword in place of
the parameter value
TIP
When you are embedding calls to stored procedures in client applications and script
files, it is advisable to pass parameters by name Reviewing and debugging the code
becomes easier that way One time we spent half a day debugging a set of nested
stored procedures to figure out why they weren’t working correctly, only to find the
problem was due to a missed parameter; all the parameter values were shifted over
one place and the wrong values ended up being passed to the wrong parameters
This resulted in the queries not finding any matching values Had the parameters
been passed by name, this issue would not have occurred This was a lesson learned
the hard way!
Input parameter values passed in can be only explicit constant values, local variables,
parameters, or, new for SQL Server 2008, table-valued parameters However, you cannot
specify a function or another expression as an input parameter value You would have to
store a return value from the function or expression value in a local variable and pass the
local variable as the input parameter Likewise, you cannot use a function or another
expression as a default value for a parameter
Trang 2Setting Default Values for Parameters
You can assign a default value to a parameter by specifying a value in the definition of the
parameter, as shown in Listing 28.11
LISTING 28.11 Assigning a Default Value for a Parameter in a Stored Procedure
ALTER PROCEDURE title_authors @state char(2) = ‘%’
AS
SELECT a.au_lname, a.au_fname, t.title
FROM titles t
INNER JOIN titleauthor ta ON t.title_id = ta.title_id
RIGHT OUTER JOIN authors a ON ta.au_id = a.au_id
WHERE a.state like @state
RETURN
GO
You can have SQL Server apply the default value for a parameter during execution by not
specifying a value or by specifying the DEFAULT keyword in the position of the parameter,
as shown in Listing 28.12
LISTING 28.12 Applying a Default Value for a Parameter When Executing a Stored Procedure
EXEC title_authors
EXEC title_authors DEFAULT
EXEC title_authors @state = DEFAULT
TIP
If you are involved in creating stored procedures that other people will use, you
proba-bly want to make the stored procedures as easy to use as possible
If you leave out a parameter that is required, SQL Server presents an error message
The myproc procedure, shown earlier in this section, requires three parameters:
@parm1, @parm2, and @parm3:
EXEC myproc
Server: Msg 201, Level 16, State 4, Procedure myproc, Line 0
Procedure ‘myproc’ expects parameter ‘@parm1’, which was not
supplied
Note that SQL Server complains only about the first missing parameter The
program-mer passes the first parameter, only to find out that more parameters are required
This is a good way to annoy a programmer or an end user
Trang 3When you execute a command-line program, you probably expect that you can use /?
to obtain a list of the parameters the program expects You can program stored
proce-dures in a similar manner by assigning NULL (or some other special value) as a default
value to the parameters and checking for that value inside the procedure The following
is an outline of a stored procedure that presents the user with information about the
parameters expected if the user doesn’t pass parameters:
CREATE PROC MyProc2
@parm1 int = NULL, @parm2 int = 32, @parm3 int = NULL
AS
IF (@parm1 IS NULL or @parm1 NOT BETWEEN 1 and 10) OR
@parm3 IS NULL
PRINT ‘Usage:
EXEC MyProc2
@parm1 int, (Required: Can be between 1 and 10)
@parm2 = 32, (Optional: Default value of 32)
@parm3 int, (Required: Any number within range)’
Processing goes here
RETURN
GO
EXEC MyProc2
GO
Usage:
EXEC MyProc2
@parm1 int, (Required: Can be between 1 and 10)
@parm2 = 32, (Optional: Default value of 32)
@parm3 int, (Required: Any number within range)
You can develop your own standards for the way the message is presented to the user,
but what is important is that the information is presented at all
To display the parameters defined for a stored procedure, you can view them in the SSMS
Object Explorer (see Figure 28.7) or by executing the sp_help stored procedure, as shown
in Listing 28.13 (Note that the output has been edited to fit the page.)
LISTING 28.13 Displaying Stored Procedure Parameters by Using sp_help
exec sp_help title_authors
Name Owner Type Created_datetime
Trang 4FIGURE 28.7 Displaying stored procedure parameters in SSMS
- - - - -
-title_authors dbo stored procedure 2008-09-15 21:15:06.540
Parameter_name Type Length Prec Scale Param_order Collation
- - - - -
-@state char 2 2 NULL 1 SQL_Latin1_General_CP1_CI_AS
You can also display the stored procedure parameters by running a query against the
INFORMATION_SCHEMA view parameters:
select substring(Parameter_NAME,1, 30) as Parameter_name,
substring (DATA_TYPE, 1, 20) as Data_Type,
CHARACTER_MAXIMUM_LENGTH as Length,
ordinal_position as param_order,
Collation_name
from INFORMATION_SCHEMA.parameters
where specific_name = ‘title_authors’
and specific_schema = ‘dbo’
order by ordinal_position
go
Trang 5Parameter_name Data_Type Length param_order Collation_name
- - - -
-@state char 2 1 SQL_Latin1_General_CP1_CI_AS
You can view parameter information for a stored procedure as well using the
sys.parameters catalog view:
select substring(p.name,1, 30) as Parameter_name,
substring (t.name, 1, 20) as Data_Type,
p.max_length as Length,
parameter_id as param_order,
default_value
from sys.parameters p
inner join sys.types t
on p.user_type_id = t.user_type_id
where p.object_id = object_id(‘title_authors’)
order by parameter_id
go
Parameter_name Data_Type Length param_order default_value
- - - -
-@state char 2 1 NULL
Passing Object Names as Parameters
In SQL Server 2008, if you pass an object name as a parameter to a stored procedure, SQL
Server attempts to treat it as a table-valued parameter unless the object name is used either
as an argument in a WHERE clause or in a dynamic SQL query For example, the code in
Listing 28.14 generates an error message when you try to create the stored procedure
LISTING 28.14 Attempting to Create a Stored Procedure by Using a Parameter to Pass in a
Table Name
CREATE proc find_data @table varchar(128)
as
select * from @table
GO
Msg 1087, Level 16, State 1, Procedure find_data, Line 4
Must declare the table variable “@table”
As you can see, when the parameter is used in the FROM clause, SQL Server expects it to be
defined as a table variable To use the value in the parameter as a table name, you can
Trang 6LISTING 28.15 Passing a Table as a Parameter to a Stored Procedure for Dynamic SQL
Execution
CREATE proc find_data @table varchar(128)
as
exec (‘select * from ‘ + @table)
return
go
exec find_data @table = ‘publishers’
go
pub_id pub_name city state country
- - - -
-0736 New Moon Books Boston MA USA
0877 Binnet & Hardley Washington DC USA
1389 Algodata Infosystems Berkeley CA USA
1622 Five Lakes Publishing Chicago IL USA
1756 Ramona Publishers Dallas TX USA
9952 Scootney Books New York NY USA
9999 Lucerne Publishing Paris NULL France
Using Wildcards in Parameters
Wildcards can be included in varchar-based input parameters and used in a LIKE clause in
a query to perform pattern matching However, you should not use the char data type for
parameters that will contain wildcard characters because SQL Server pads spaces onto the
value passed in to the parameter to expand it to the specified size of the char data type
For example, if you declared an @lastname parameter as char(40) and passed in ’S%’, SQL
Server would search not for a string starting with ’S’ but for a string starting with ’S’,
any characters, and ending with up to 38 spaces This would likely not match any actual
data values
Also, to increase the flexibility of a stored procedure that searches for character strings,
you can default the parameter to ’%’, as in the following example:
IF EXISTS ( SELECT * FROM sys.procedures
WHERE schema_id = schema_id(‘dbo’) AND name = N’find_authors’) DROP PROCEDURE dbo.find_authors
GO
create proc find_authors @lastname varchar(40) = ‘%’
as
select au_id, au_lname, au_fname
Trang 7from authors
where au_lname like @lastname
order by au_lname, au_fname
This procedure, if passed no parameter, returns data for all authors in the authors table If
passed a string containing wildcard characters, this procedure returns data for all authors
matching the search pattern specified If a string containing no wildcards is passed, the
query performs a search for exact matches against the string value
Unfortunately, wildcard searches can be performed only against character strings If you
want to have similar flexibility searching against a numeric value, such as an integer, you
can default the value to NULL and when the parameter is NULL, compare the column with
itself, as shown in the following example:
IF EXISTS ( SELECT * FROM sys.procedures
WHERE schema_id = schema_id(‘dbo’) AND name = N’find_titles_by_sales’) DROP PROCEDURE dbo.find_titles_by_sales
GO
create proc find_titles_by_sales @ytd_sales int = null
as
select title_id, title, ytd_sales
from titles
where ytd_sales = isnull(@ytd_sales, ytd_sales)
However, the problem with this approach is that the procedure returns all rows from the
titles table except those in which ytd_sales contains a NULL value The reason is that
NULL is never considered equal to NULL; you cannot compare an unknown value with
another unknown value To return all rows, including those in which ytd_sales is NULL,
you need to implement a dual-query solution, as in the following example:
IF EXISTS ( SELECT * FROM sys.procedures
WHERE schema_id = schema_id(‘dbo’) AND name = N’find_titles_by_sales’) DROP PROCEDURE dbo.find_titles_by_sales
GO
create proc find_titles_by_sales @ytd_sales int = null
as
if @ytd_sales is null
select title_id, title, ytd_sales
from titles
else
select title_id, title, ytd_sales
from titles
where ytd_sales= @ytd_sales
Trang 8Using Table-Valued Parameters
In previous versions of SQL Server, it was not possible to share the contents of table
vari-ables between stored procedures SQL Server 2008 changes that with the introduction of
table-valued parameters, which allow you to pass table variables to stored procedures
Table-valued parameters provide more flexibility and, in many cases, better performance
than temporary tables as a means to pass result sets between stored procedures
NOTE
For more information on using temporary tables and the table data type in stored
pro-cedures, see Chapter 44
Table-valued parameters provide many of the same performance advantages as table data
types Table-valued parameters also share some of the same restrictions as table variables,
such as SQL Server not maintaining statistics on table-valued parameters and table-valued
parameters not permitted as the target of a SELECT INTO or INSERT EXEC statement In
addition, table-valued parameters can be passed only as READONLY input parameters to
stored procedures DML operations, such as UPDATE, INSERT, and DELETE, cannot be
performed on table-valued parameters within the body of a stored procedure
To create and use table-valued parameters, you must first create a user-defined table type
and define the table structure You do so using the CREATE TYPE command, as in the
following example:
if exists (select * from sys.systypes t where t.name = ‘ytdsales_tabletype’
and t.uid = USER_ID(‘dbo’)) drop type ytdsales_tabletype
go
CREATE TYPE ytdsales_tabletype AS TABLE
(title_id char(6),
title varchar(50),
pubdate date,
ytd_sales int)
go
After the table data type is created, you can use it for declaring local table variables and for
stored procedure parameters To use the table-valued parameter in a procedure, you create
a procedure to receive and access data through a table-valued parameter:
/* Create a procedure to receive data for the table-valued parameter */
if OBJECT_ID(‘tab_parm_test’) is not null
drop proc tab_parm_test
go
create proc tab_parm_test
Trang 9@pubdate datetime = null,
@sales_minimum int = 0,
@ytd_sales_tab ytdsales_tabletype READONLY
as
set nocount on
if @pubdate is null
if no date is specified, set date to last year
set @pubdate = dateadd(month, -12, getdate())
select * from @ytd_sales_tab
where pubdate > @pubdate
and ytd_sales >= @sales_minimum
return
go
Then, when calling that stored procedure, you declare a local table variable using the table
data type defined previously, populate the table variable with data, and then pass the table
variable to the stored procedure:
/* Declare a variable that references the type */
declare @ytd_sales_tab ytdsales_tabletype
/* Add data to the table variable */
insert @ytd_sales_tab
select title_id, convert(varchar(50), title), pubdate, ytd_sales
from titles
/* Pass the table variable populated with data to a stored procedure */
exec tab_parm_test ‘6/1/2001’, 10000, @ytd_sales_tab
go
title_id title ytd_sales
- -
-BU2075 You Can Combat Computer Stress! 18722
MC3021 The Gourmet Microwave 22246
TC4203 Fifty Years in Buckingham Palace Kitchens 15096
Using Output Parameters
If a calling batch passes a variable as a parameter to a stored procedure and that parameter
is modified inside the procedure, the modifications are not passed to the calling batch
unless you specify the OUTPUT keyword for the parameter when executing the stored
proce-dure
Trang 10If you want a procedure to be able to pass parameter values out from the procedure, you
need to use the keyword OUTPUT when creating the procedure The following example
shows a stored procedure that accepts two parameters, one of which is used as an
output parameter:
IF EXISTS ( SELECT * FROM sys.procedures
WHERE schema_id = schema_id(‘dbo’) AND name = N’ytd_sales’)
DROP PROCEDURE dbo.ytd_sales
GO
CREATE PROC ytd_sales
@title varchar(80), @ytd_sales int OUTPUT
AS
SELECT @ytd_sales = ytd_sales
FROM titles
WHERE title = @title
RETURN
The calling batch (or stored procedure) needs to declare a variable to store the returned
value The execute statement must include the OUTPUT keyword as well, or the
modifications won’t be reflected in the calling batch’s variable:
DECLARE @sales_up_to_today int
EXEC ytd_sales ‘Life Without Fear’, @sales_up_to_today OUTPUT
PRINT ‘Sales this year until today’’s date: ‘ +
CONVERT(VARCHAR(10), @sales_up_to_today) + ‘.’
Sales this year until today’s date: 111
You can also pass the output parameter by name:
DECLARE @sales_up_to_today int
EXEC ytd_sales ‘Life Without Fear’,
@ytd_sales = @sales_up_to_today OUTPUT
PRINT ‘Sales this year until today’’s date: ‘ +
CONVERT(VARCHAR(10), @sales_up_to_today) + ‘.’
Note that when you pass an output parameter by name, the parameter name (@ytd_sales,
in this example) is listed on the left side of the expression, and the local variable
(@sales_up_to_today), which is set equal to the value of the output parameter, is on the
right side of the expression An output parameter can also serve as an input parameter
Output parameters can also be passed back and captured in a client application by using
ADO, ODBC, OLE DB, and so on