Tải bản đầy đủ (.pdf) (10 trang)

Microsoft SQL Server 2008 R2 Unleashed- P94 pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (374.51 KB, 10 trang )

ptg
874
CHAPTER 28 Creating and Managing Stored Procedures
FIGURE 28.1 Using the Specify Values for Template Parameters dialog in SSMS.
One thing you might notice about the stored procedure template is that it contains
template parameters for parameter names, procedure name, author name, create date, and
so on. These template parameters are in the format
<parameter, type, value>:
. parameter_name is the name of the template parameter in the script.
. data_type is the optional data type of the template parameter.
. value is the default value to be used to replace every occurrence of the template
parameter in the script
You can auto substitute values for template parameters by selecting Query, Specify Values
for Template Parameters or by pressing Ctrl+Shift+M. This brings up the dialog shown in
Figure 28.1.
You enter the values for the template parameters in the Value column and then click OK.
SSMS then substitutes any values you specified wherever the template parameter is used
within the template.
An alternative way to create a stored procedure from a template is to use the Template
Explorer in SSMS. You can open the Template Explorer by selecting View, Template
Explorer in SSMS or by pressing Ctrl+Alt+T. The Template Explorer window appears in
SSMS, as shown in Figure 28.2.
You can double-click the name of the stored procedure template you want to use or right-
click the desired template and then select Open. SSMS opens a new query window, popu-
lated with the template code.
Download from www.wowebook.com
ptg
875
Creating Stored Procedures
FIGURE 28.2 Using the Template Explorer for creating stored procedures in SSMS.
28


NOTE
It is also possible to edit the provided stored procedure templates available in the
Template Explorer by right-cli cking them and selecting the Edit option. You can then c us-
tomize the templates to include code fragments, comments, or structure that is more
to your preference and save the changes to the template file. However, it is generally
recommended that you not modify the provided templates and instead create your own
custom templates.
Creating Custom Stored Procedure Templates
To create a custom stored procedure template, right-click the Stored Procedure folder in
the Template Explorer and select New. SSMS then creates an entry in the Template
Explorer, and you can specify the name for the template.
To begin adding code to the template, right-click the template and select Edit. This opens
a query window in which you can start entering the new template code. Probably the best
way to get started is to copy the template code from one of the templates provided with
SQL Server 2008 and then modify it as you desire. You then select File, Save to save the
template code to the file.
Listing 28.3 shows an example of a new stored procedure template.
Download from www.wowebook.com
ptg
876
CHAPTER 28 Creating and Managing Stored Procedures
LISTING 28.3 An Example of Custom Stored Procedure Template
=============================================
Create basic stored procedure template
=============================================
Drop stored procedure if it already exists
IF EXISTS (
SELECT *
FROM sys.procedures
WHERE schema_id = schema_id(‘dbo’)

AND name = N’<Proc_Name, sysname, myproc>’
)
DROP PROCEDURE <Schema_Name, sysname, dbo>.<Proc_Name, sysname, myproc>
GO
=============================================
Author: <Author,,Name>
Create date: <Create Date,,>
Description: <Description,,>
=============================================
CREATE PROCEDURE <Schema_Name, sysname, dbo>.<Proc_Name, sysname, myproc>
— Add the parameters for the stored procedure here
<@param1, sysname, @p1> <param1_type, , int> = <param1_default, , 0>,
<@param2, sysname, @p2> <param2_type, , int> = <param2_default, , 0>,
<@param3, sysname, @p3> <param3_type, , int> OUTPUT
AS
BEGIN
SET NOCOUNT ON added to prevent extra result sets from
interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @trancnt int
SELECT @trancnt = @@TRANCOUNT
if @trancnt = 0
BEGIN TRAN <Proc_Name, sysname, myproc>
else
SAVE TRAN <Proc_Name, sysname, myproc>
/* Insert processing code here */
if (@@error != 0) check for error condition
begin
rollback to savepoint, or begin tran
rollback tran <Proc_Name, sysname, myproc>

return error code indicating rollback
Download from www.wowebook.com
ptg
877
Creating Stored Procedures
28
return -101
end
/* Insert more processing here if required */
set value of output parameter
set <@param3,sysname, @p3> = <@param1,sysname, @p1> + <@param2,sysname, @p2>
if @trancnt = 0 this proc issued begin tran
commit tran, decrement @@trancount to 0
commit tran <Proc_Name, sysname, myproc>
commit not required with save tran
return 0 /* successful return */
END
GO
— =============================================
— Example to execute the stored procedure
— =============================================
DECLARE <@output_variable, sysname, @p3_output> <output_datatype, , int>
EXECUTE <Schema_name, sysname, dbo>.<Proc_name, sysname, myproc>
<@param1, sysname, @p1> = <param1_value, , 1>,
<@param2, sysname, @p2> = <param2_value, , 1>,
<@param3, sysname, @p3> = <@output_variable, sysname, @p3_output> OUTPUT
SELECT <@output_variable, sysname, @p3_output>
GO
After you define a custom stored procedure template, you can use it as you would use the
built-in templates. You can double-click it or right-click and select Open, and SSMS opens

a new query window with a new stored procedure creation script based on the custom
template. If you use the default values for the template parameters, after the parameter
substitution, the
CREATE PROCEDURE script looks like the one in Listing 28.4.
LISTING 28.4 An Example of a CREATE PROCEDURE Script Generated from the Custom
Stored Procedure Template
=============================================
Create basic stored procedure template
=============================================
Download from www.wowebook.com
ptg
878
CHAPTER 28 Creating and Managing Stored Procedures
Drop stored procedure if it already exists
IF EXISTS (
SELECT *
FROM sys.procedures
WHERE schema_id = schema_id(‘dbo’)
AND name = N’myproc’
)
DROP PROCEDURE dbo.myproc
GO
=============================================
Author: Name
Create date:
Description:
=============================================
CREATE PROCEDURE dbo.myproc
— Add the parameters for the stored procedure here
@p1 int = 0,

@p2 int = 0,
@p3 int OUTPUT
AS
BEGIN
SET NOCOUNT ON added to prevent extra result sets from
interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @trancnt int
SELECT @trancnt = @@TRANCOUNT
if @trancnt = 0
BEGIN TRAN myproc
else
SAVE TRAN myproc
/* Insert processing code here */
if (@@error != 0) check for error condition
begin
rollback to savepoint, or begin tran
rollback tran myproc
return error code indicating rollback
return -101
end
/* Insert more processing here if required */
Download from www.wowebook.com
ptg
879
Creating Stored Procedures
28
set value of output parameter
set @p3 = @p1 + @p2
if @trancnt = 0 this proc issued begin tran

commit tran, decrement @@trancount to 0
commit tran myproc
commit not required with save tran
return 0 /* successful return */
END
GO
=============================================
Example to execute the stored procedure
=============================================
DECLARE @p3_output int
EXECUTE dbo.myproc
@p1 = 1,
@p2 = 1,
@p3 = @p3_output OUTPUT
SELECT @p3_output
GO
Temporary Stored Procedures
SQL Server enables you to create private and global temporary stored procedures.
Temporary stored procedures are analogous to temporary tables in that they can be
created with the
# and ## prefixes added to the procedure name. The # prefix denotes a
local temporary stored procedure; ## denotes a global temporary stored procedure. A local
temporary stored procedure can be executed only by the connection that created it, and
the procedure is automatically deleted when the connection is closed. A global temporary
stored procedure can be accessed by multiple connections and exists until the connection
used by the user who created the procedure is closed and any currently executing versions
of the procedure by any other connections are completed.
If a stored procedure not prefixed with
# or ## is created directly in the tempdb database,
the stored procedure exists until SQL Server is shut down. Procedures created directly in

tempdb continue to exist even after the creating connection is terminated.
Download from www.wowebook.com
ptg
880
CHAPTER 28 Creating and Managing Stored Procedures
Temporary stored procedures are provided for backward compatibility with earlier versions
of SQL Server that did not support the reuse of execution plans for T-SQL statements or
batches. Applications connecting to SQL Server 2000 and higher should use the
sp_executesql system stored procedure to execute dynamic SQL statements instead of
creating temporary stored procedures.
TIP
It is strongly recommended that sp_executesql be used instead of temporary stored
procedures. Excessive use of temporary stored procedures can lead to locking con-
tention on the system tables in
tempdb, which can adversely affect overall system per-
formance. For more information on using sp_executesql, see Chapter 44, "Advanced
Stored Procedure Programming and Optimization."
Executing Stored Procedures
To execute a stored procedure, you simply invoke it by using its name (the same way you
probably have already executed system stored procedures, such as sp_help). If the execu-
tion of the stored procedure isn’t the first statement in a batch, you need to precede the
procedure name with the
EXEC keyword. Following is the basic syntax for executing stored
procedures:
[EXEC[UTE]] [@status =] [schema].procedure_name[; number]
[[@param_name =] expression [output][, ]]
[WITH RECOMPILE]
NOTE
The reason you need the EXEC keyword when invoking a stored procedure in a batch or
other stored procedure is quite simple. SQL Server parses the commands sent to it in

a batch by searching for keywords. Stored procedure names aren’t keywords. If SQL
Server finds a procedure name among the SQL statements, chances are that SQL
Server will return an error message because it tries to treat it as part of the preceding
command. Sometimes the execution is successful, but SQL Server doesn’t execute
what you want. Consider this example:
SELECT * FROM titles
sp_help
The SELECT statement runs fine, but the procedure is not executed. The reason is
that sp_help ends up being used as a table alias for the titles table in the
SELECT statement.
However, if you precede the procedure name with EXEC, like this, you get the
expected behavior:
SELECT * FROM titles
Download from www.wowebook.com
ptg
881
Executing Stored Procedures
28
EXEC sp_help
Why don’t you have to put EXEC in front of the procedure name if the procedure is the
first statement in a batch? If SQL Server doesn’t recognize the first string in a batch, it
simply assumes that it is a name of a stored procedure. For example, execute the
following string and notice the error message:
Dsfdskgkghk
go
Msg 2812, Level 16, State 62, Line 1
Could not find stored procedure ‘Dsfdskgkghk’.
As good programming practice, it is best to always precede stored procedures with the
EXEC keyword. This way, it will always work as expected, whether or not it’s the first
statement in a batch.

Executing Procedures in SSMS
To execute a stored procedure in SSMS, open the object tree for the database, open the
Programmability folder, and open the Stored Procedures folder. Then right-click the
stored procedure, and from the context menu, choose Execute Stored Procedure. SSMS
then presents you with the Execute Procedure dialog, as shown in Figure 28.3. In this
window, you can enter values for any parameters contained in the stored procedure. If you
want to pass a
NULL value to a parameter, you need to be sure to place a check mark in the
Pass Null Value check box for that parameter.
After you specify values for all the parameters, SSMS opens a new query window with the
generated execute statement and automatically executes it. It displays any results in the
Results window. If the stored procedure contains output parameters, SSMS generates local
variables for the output parameters and uses a
SELECT statement to display the values
returned to the output parameters. Listing 28.5 shows an example of the execute script
and its results for the procedure invoked in Figure 28.3 (this procedure is the one gener-
ated from the custom procedure template, as shown in Listing 28.4).
LISTING 28.5 A Procedure Execution Script Generated by SSMS
USE [bigpubs2008]
GO
DECLARE @return_value int,
@p3 int
EXEC @return_value = [dbo].[myproc]
@p1 = 100,
@p2 = 200,
@p3 = @p3 OUTPUT
Download from www.wowebook.com
ptg
882
CHAPTER 28 Creating and Managing Stored Procedures

FIGURE 28.3 Using the Execute Procedure dialog in SSMS.
SELECT @p3 as N’@p3’
SELECT ‘Return Value’ = @return_value
GO
@p3

300
Return Value

0
Execution Context and the EXECUTE AS Clause
Normally, stored procedures execute within the security context of the current user. The
user must have execute permission on the procedure and if the objects referenced within
the stored procedure are not owned by the user who created the stored procedure, the
current user must also have the necessary permissions granted on the referenced objects.
The current user does not inherit the permissions of the procedure creator. The only
Download from www.wowebook.com
ptg
883
Executing Stored Procedures
28
exception to this occurs when the objects referenced by a stored procedure are owned by
the same user who created the stored procedure. In this case, permissions on the refer-
enced objects in the stored procedure are dependent on the ownership chain that exists
between the calling procedure and referenced objects. For example, if the creator of a
stored procedure also owns the table that it references, the user executing the stored
procedure inherits the rights on the referenced table from the owner within the context of
the stored procedure, without having to be granted explicit rights on the table by the
table owner.
However, there are limitations to using ownership chaining alone for inheriting access

permissions:
. The rights inherited by ownership chaining apply only to DML statements:
SELECT,
INSERT, UPDATE, and DELETE.
. The owners of the calling and called objects must be the same.
. The rights inherited by ownership chaining do not apply to dynamic queries inside
the stored procedure.
In SQL Server 2008, you can implicitly define the execution context of functions (except
inline table-valued functions), stored procedures, and triggers by specifying the EXECUTE
AS clause. The EXECUTE AS clause allows you to go beyond ownership chaining to specify
the security context under which a stored procedure will execute and what access rights
the user will have on the referenced objects. The
EXECUTE AS clause allows you to specify
explicitly the security context under which the stored procedure will execute. In other
words, it allows you to specify which user account SQL Server should use to validate
permissions on the database objects referenced by the stored procedure. The user execut-
ing the stored procedure, in effect, impersonates the user specified in the
EXECUTE AS
clause within the context of the execution of the stored procedure.
The EXECUTE AS clause can be specified when the stored procedure is created to set the
default security context for all users when executing the stored procedure. Alternatively,
the
EXECUTE AS clause can be specified explicitly within the stored procedure code or
within each individual user session. When specified in a user session, the security context
switches to that specified until the connection is closed, a
REVERT statement is run, or
another EXECUTE AS statement is run.
The syntax of the EXECUTE AS clause for stored procedures is as follows:
{ EXEC | EXECUTE } AS { CALLER | SELF | OWNER | ‘user_name’ }
You can specify the following security context options when using the EXECUTE AS clause:

. CALLER—This option specifies that the statements inside the stored procedure are
executed in the context of the caller of the module (that is, the current user). The
user executing the stored procedure must have execute permission on the stored
procedure and also permissions on any database objects that are referenced by the
stored procedure that are not owned by the procedure creator.
CALLER is the default
behavior for all stored procedures, and it is the same as SQL Server 2000 behavior.
Download from www.wowebook.com

×