What’s New in SQL Server System and Database Administration
System Administrator Responsibilities
System Databases
System Tables
System Views
System Stored Procedures
Summary
8 Installing SQL Server 2008
What’s New in Installing SQL Server 2008
Installation Requirements
Installation Walkthrough
Installing SQL Server Using a Configuration File
Installing Service Packs and Cumulative Updates
Slipstream Installations
Summary
9 Upgrading to SQL Server 2008
What’s New in Upgrading SQL Server
Using the SQL Server Upgrade Advisor (UA)
Destination: SQL Server 2008 or SQL Server 2008 R2
Upgrading Using a Configuration File
Slipstreaming Upgrades
Upgrading Other SQL Server Components
Summary
10 Client Installation and Configuration
What’s New in Client Installation and Configuration
Client/Server Networking Considerations
Client Installation
Client Configuration
Client Data Access Technologies
Summary
11 Security and User Administration
What’s New in Security and User Administration
An Overview of SQL Server Security
Authentication Methods
Managing Principals
Managing Securables
Managing Permissions
Managing SQL Server Logins
Managing SQL Server Users
Managing Database Roles
Managing SQL Server Permissions
The Execution Context
Summary
12 Data Encryption
What’s New in Data Encryption
An Overview of Data Security
An Overview of Data Encryption
SQL Server Key Management
Column-Level Encryption
Transparent Data Encryption
Column-Level Encryption Versus Transparent Data Encryption
Summary
13 Security and Compliance
Exposure and Risk
Across the Life Cycle
The Security Big Picture
Identity Access Management Components
Compliance and SQL Server
SQL Server Auditing
Setting Up Auditing via T-SQL
SQL Injection Is Easy to Do
Summary
14 Database Backup and Restore
What’s New in Database Backup and Restore
Developing a Backup and Restore Plan
Types of Backups
Recovery Models
Backup Devices
Backing Up a Database
Backing Up the Transaction Log
Backup Scenarios
Restoring Databases and Transaction Logs
Restore Scenarios
Additional Backup Considerations
Summary
15 Database Mail
What’s New in Database Mail
Setting Up Database Mail
Sending and Receiving with Database Mail
Using SQL Server Agent Mail
Related Views and Procedures
Summary
16 SQL Server Scheduling and Notification
What’s New in Scheduling and Notification
Configuring the SQL Server Agent
Viewing the SQL Server Agent Error Log
SQL Server Agent Security
Managing Operators
Managing Jobs
Managing Alerts
Scripting Jobs and Alerts
Multiserver Job Management
Event Forwarding
Summary
17 Administering SQL Server 2008 with PowerShell
What’s New with PowerShell
Overview of PowerShell
PowerShell Scripting Basics
PowerShell in SQL Server 2008
Step-By-Step Examples
Summary
18 SQL Server High Availability
What’s New in High Availability
What Is High Availability?
The Fundamentals of HA
Building Solutions with One or More HA Options
Other HA Techniques That Yield Great Results
High Availability from the Windows Server Family Side
Summary
19 Replication
What’s New in Data Replication
What Is Replication?
The Publisher, Distributor, and Subscriber Magazine Metaphor
Replication Scenarios
Subscriptions
Replication Agents
Planning for SQL Server Data Replication
SQL Server Replication Types
Basing the Replication Design on User Requirements
Setting Up Replication
Scripting Replication
Monitoring Replication
Summary
20 Database Mirroring
What’s New in Database Mirroring
What Is Database Mirroring?
Roles of the Database Mirroring Configuration
Setting Up and Configuring Database Mirroring
Testing Failover from the Principal to the Mirror
Client Setup and Configuration for Database Mirroring
Migrate to Database Mirroring 2008 as Fast as You Can
Using Replication and Database Mirroring Together
Using Database Snapshots from a Mirror for Reporting
Summary
21 SQL Server Clustering
What’s New in SQL Server Clustering
How Microsoft SQL Server Clustering Works
Installing SQL Server Clustering
Summary
22 Administering Policy-Based Management
Introduction to Policy-Based Management
Policy-Based Management Concepts
Implementing Policy-Based Management
Sample Templates and Real-World Examples
Policy-Based Management Best Practices
Summary
Part IV: Database Administration
23 Creating and Managing Databases
What’s New in Creating and Managing Databases
Data Storage in SQL Server
Database Files
Creating Databases
Setting Database Options
Managing Databases
Summary
24 Creating and Managing Tables
What’s New in SQL Server 2008
Creating Tables
Defining Columns
Defining Table Location
Defining Table Constraints
Modifying Tables
Dropping Tables
Using Partitioned Tables
Creating Temporary Tables
Summary
25 Creating and Managing Indexes
What’s New in Creating and Managing Indexes
Types of Indexes
Creating Indexes
Managing Indexes
Dropping Indexes
Online Indexing Operations
Indexes on Views
Summary
26 Implementing Data Integrity
What’s New in Data Integrity
Types of Data Integrity
Enforcing Data Integrity
Using Constraints
Rules
Defaults
Summary
27 Creating and Managing Views in SQL Server
What’s New in Creating and Managing Views
Definition of Views
Using Views
Creating Views
Managing Views
Data Modifications and Views
Partitioned Views
Indexed Views
Summary
28 Creating and Managing Stored Procedures
What’s New in Creating and Managing Stored Procedures
Advantages of Stored Procedures
Creating Stored Procedures
Executing Stored Procedures
Deferred Name Resolution
Viewing Stored Procedures
Modifying Stored Procedures
Using Input Parameters
Using Output Parameters
Returning Procedure Status
Debugging Stored Procedures Using SQL Server Management Studio
Using System Stored Procedures
Startup Procedures
Summary
29 Creating and Managing User-Defined Functions
What’s New in SQL Server 2008
Why Use User-Defined Functions?
Types of User-Defined Functions
Creating and Managing User-Defined Functions
Rewriting Stored Procedures as Functions
Creating and Using CLR Functions
Summary
30 Creating and Managing Triggers
What’s New in Creating and Managing Triggers
Using DML Triggers
Using DDL Triggers
Using CLR Triggers
Using Nested Triggers
Using Recursive Triggers
Summary
31 Transaction Management and the Transaction Log
What’s New in Transaction Management
What Is a Transaction?
How SQL Server Manages Transactions
Defining Transactions
Transactions and Batches
Transactions and Stored Procedures
Transactions and Triggers
Transactions and Locking
Coding Effective Transactions
Transaction Logging and the Recovery Process
Long-Running Transactions
Bound Connections
Distributed Transactions
Summary
32 Database Snapshots
What’s New with Database Snapshots
What Are Database Snapshots?
Limitations and Restrictions of Database Snapshots
Copy-on-Write Technology
When to Use Database Snapshots
Setup and Breakdown of a Database Snapshot
Reverting to a Database Snapshot for Recovery
Setting Up Snapshots Against a Database Mirror
Database Snapshots Maintenance and Security Considerations
Summary
33 Database Maintenance
What’s New in Database Maintenance
The Maintenance Plan Wizard
Managing Maintenance Plans Without the Wizard
Executing a Maintenance Plan
Maintenance Without a Maintenance Plan
Database Maintenance Policies
Summary
Part V: SQL Server Performance and Optimization
34 Data Structures, Indexes, and Performance
What’s New for Data Structures, Indexes, and Performance
Understanding Data Structures
Database Files and Filegroups
Database Pages
Space Allocation Structures
Data Compression
Understanding Table Structures
Understanding Index Structures
Data Modification and Performance
Index Utilization
Index Selection
Evaluating Index Usefulness
Index Statistics
SQL Server Index Maintenance
Index Design Guidelines
Indexed Views
Indexes on Computed Columns
Filtered Indexes and Statistics
Choosing Indexes: Query Versus Update Performance
Identifying Missing Indexes
Identifying Unused Indexes
Summary
35 Understanding Query Optimization
What’s New in Query Optimization
What Is the Query Optimizer?
Query Compilation and Optimization
Query Analysis
Row Estimation and Index Selection
Join Selection
Execution Plan Selection
Query Plan Caching
Other Query Processing Strategies
Parallel Query Processing
Common Query Optimization Problems
Managing the Optimizer
Summary
36 Query Analysis
What’s New in Query Analysis
Query Analysis in SSMS
SSMS Client Statistics
Using the SET SHOWPLAN Options
Using sys.dm_exec_query_plan
Query Statistics
Query Analysis with SQL Server Profiler
Summary
37 Locking and Performance
What’s New in Locking and Performance
The Need for Locking
Transaction Isolation Levels in SQL Server
The Lock Manager
Monitoring Lock Activity in SQL Server
SQL Server Lock Types
SQL Server Lock Granularity
Lock Compatibility
Locking Contention and Deadlocks
Table Hints for Locking
Optimistic Locking
Summary
38 Database Design and Performance
What’s New in Database Design and Performance
Basic Tenets of Designing for Performance
Logical Database Design Issues
Denormalizing a Database
Database Filegroups and Performance
RAID Technology
SQL Server and SAN Technology
Summary
39 Monitoring SQL Server Performance
What’s New in Monitoring SQL Server Performance
Performance Monitoring Tools
A Performance Monitoring Approach
Summary
40 Managing Workloads with the Resource Governor
Overview of Resource Governor
Resource Governor Components
Configuring Resource Governor
Monitoring Resource Usage
Modifying Your Resource Governor Configuration
Summary
41 A Performance and Tuning Methodology
The Full Architectural Landscape
Primary Performance and Tuning Handles
A Performance and Tuning Methodology
Performance and Tuning Design Guidelines
Tools of the Performance and Tuning Trade
Summary
Part VI: SQL Server Application Development
42 What’s New for Transact-SQL in SQL Server 2008
MERGE Statement
Insert over DML
GROUP BY Clause Enhancements
Variable Assignment in DECLARE Statement
Compound Assignment Operators
Row Constructors
New date and time Data Types and Functions
Table-Valued Parameters
Hierarchyid Data Type
Using FILESTREAM Storage
Sparse Columns
Spatial Data Types
Change Data Capture
Change Tracking
Summary
43 Transact-SQL Programming Guidelines, Tips, and Tricks
General T-SQL Coding Recommendations
General T-SQL Performance Recommendations
T-SQL Tips and Tricks
In Case You Missed It: New Transact-SQL Features in SQL Server 2005
The xml Data Type
The max Specifier
TOP Enhancements
The OUTPUT Clause
Common Table Expressions
Ranking Functions
PIVOT and UNPIVOT
The APPLY Operator
TRY...CATCH Logic for Error Handling
The TABLESAMPLE Clause
Summary
44 Advanced Stored Procedure Programming and Optimization
T-SQL Stored Procedure Coding Guidelines
Using Cursors in Stored Procedures
Nested Stored Procedures
Using Temporary Tables in Stored Procedures
Using Remote Stored Procedures
Stored Procedure Performance
Using Dynamic SQL in Stored Procedures
Installing and Using .NET CLR Stored Procedures
Using Extended Stored Procedures
Summary
45 SQL Server and the .NET Framework
What’s New in SQL Server 2008 and the .NET Framework
Getting Comfortable with ADO.NET 3.5 and SQL Server 2008
Developing with LINQ to SQL
Using ADO.NET Data Services
Leveraging the Microsoft Sync Framework
Summary
46 SQLCLR: Developing SQL Server Objects in .NET
What’s New for SQLCLR in SQL Server 2008
Developing Custom Managed Database Objects
Summary
47 Using XML in SQL Server 2008
What’s New in Using XML in SQL Server 2008
Understanding XML
Relational Data As XML: The FOR XML Modes
XML As Relational Data: Using OPENXML
Using the xml Data Type
Indexing and Full-Text Indexing of xml Columns
Summary
48 SQL Server Web Services
What’s New in SQL Server Web Services
Web Services Migration Path
Web Services History and Overview
Building Web Services
Examples: A C# Client Application
Using Catalog Views and System Stored Procedures
Controlling Access Permissions
Summary
49 SQL Server Service Broker
What’s New in Service Broker
Understanding Distributed Messaging
Designing a Sample System
Understanding Service Broker Constructs
Service Broker Routing and Security
Troubleshooting SSB Applications with ssbdiagnose.exe
Related System Catalogs
Summary
50 SQL Server Full-Text Search
What’s New in SQL Server 2008 Full-Text Search
Upgrade Options in SQL Server 2008
How SQL Server FTS Works
Implementing SQL Server 2008 Full-Text Catalogs
Setting Up a Full-Text Index
Full-Text Searches
Full-Text Search Maintenance
Full-Text Search Performance
Full-Text Search Troubleshooting
Summary
Part VII: SQL Server Business Intelligence Features
51 SQL Server 2008 Analysis Services
What’s New in SSAS
Understanding SSAS and OLAP
Understanding the SSAS Environment Wizards
An Analytics Design Methodology
An OLAP Requirements Example: CompSales International
Summary
52 SQL Server Integration Services
What’s New with SSIS
SSIS Basics
SSIS Architecture and Concepts
SSIS Tools and Utilities
A Data Transformation Requirement
Running the SSIS Wizard
The SSIS Designer
The Package Execution Utility
Connection Projects in Visual Studio
Change Data Capture Addition with R2
Using bcp
Logged and Nonlogged Operations
Summary
53 SQL Server 2008 Reporting Services
What’s New in SSRS 2008
Reporting Services Architecture
Installing and Configuring SSRS
Developing Reports
Management and Security
Performance and Monitoring
Summary
Part VIII: Bonus Chapters
54 Managing Linked and Remote Servers
What’s New in Managing Linked and Remote Servers
Managing Remote Servers
Linked Servers
Adding, Dropping, and Configuring Linked Servers
Mapping Local Logins to Logins on Linked Servers
Obtaining General Information About Linked Servers
Executing a Stored Procedure via a Linked Server
Setting Up Linked Servers Using SQL Server Management Studio
Summary
55 Configuring, Tuning, and Optimizing SQL Server Options
What’s New in Configuring, Tuning, and Optimizing SQL Server Options
SQL Server Instance Architecture
Configuration Options
Fixing an Incorrect Option Setting
Setting Configuration Options with SSMS
Obsolete Configuration Options
Configuration Options and Performance
Database Engine Tuning Advisor
Data Collection Sets
Summary
56 SQL Server Disaster Recovery Planning
What’s New in SQL Server Disaster Recovery Planning
How to Approach Disaster Recovery
Microsoft SQL Server Options for Disaster Recovery
The Overall Disaster Recovery Process
Have You Detached a Database Recently?
Third-Party Disaster Recovery Alternatives
Summary
Index
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y-Z
Nội dung
ptg 894 CHAPTER 28 Creating and Managing Stored Procedures Processing 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. Download from www.wowebook.com ptg 895 Using Input Parameters 28 Setting 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 Ser ver 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. Download from www.wowebook.com ptg 896 CHAPTER 28 Creating and Managing Stored Procedures When 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 standar ds for t he way t he 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 Download from www.wowebook.com ptg 897 Using Input Parameters 28 FIGURE 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 Download from www.wowebook.com ptg 898 CHAPTER 28 Creating and Managing Stored Procedures Parameter_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 build a dynamic SQL query similar to the example shown in Listing 28.15. Download from www.wowebook.com ptg 899 Using Input Parameters 28 LISTING 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 Download from www.wowebook.com ptg 900 CHAPTER 28 Creating and Managing Stored Procedures from 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 Download from www.wowebook.com ptg 901 Using Input Parameters 28 Using 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 Download from www.wowebook.com ptg 902 CHAPTER 28 Creating and Managing Stored Procedures @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. Download from www.wowebook.com ptg 903 Using Output Parameters 28 If 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. Download from www.wowebook.com . 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. 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. 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