Vous êtes sur la page 1sur 31

Merging Data and Passing Tables

10-1

Module 10
Merging Data and Passing Tables
Contents:
Lesson 1: Using the MERGE Statement Lesson 2: Implementing Table Types Lesson 3: Using TABLE Types As Parameters Lab 10: Passing Tables and Merging Data 10-3 10-14 10-22 10-26

10-2

Implementing a Microsoft SQL Server 2008 R2 Database

Module Overview

Each time a client application makes a call to a SQL Server system, considerable delay is encountered at the network layer. The basic delay is unrelated to the amount of data being passed. It relates to the latency of the network. For this reason, it is important to minimize the number of times that a client needs to call a server for a given amount of data that must be passed between them. Each call is termed a "roundtrip". In this module you will review the techniques that provide the ability to process sets of data rather than individual rows. You will then see how these techniques can be used in combination with TABLE parameter types to minimize the number of required stored procedure calls in typical applications.

Objectives
After completing this lesson, you will be able to: Use the MERGE statement Implement table types Use TABLE types as parameters

Merging Data and Passing Tables

10-3

Lesson 1

Using the MERGE Statement

A very common requirement when coding in T-SQL is the need to update a row if it exists but to insert the row if it does not already exist. SQL Server 2008 introduced the MERGE statement that provides this ability plus the ability to process entire sets of data rather than processing row by row or in several separate set-based statements. This leads to much more efficient execution and simplifies the required coding. In this lesson, you will investigate the use of the MERGE statement and the use of the most common options associated with the statement.

Objectives
After completing this lesson, you will be able to: Explain the role of the MERGE statement Describe how to use the WHEN MATCHED clause Describe how to use the WHEN NOT MATCHED BY TARGET clause Describe how to use the WHEN NOT MATCHED BY SOURCE clause Explain the role of the OUTPUT clause and $action Describe MERGE determinism and performance

10-4

Implementing a Microsoft SQL Server 2008 R2 Database

MERGE Statement

Key Points
The MERGE statement is most commonly used to insert data that does not already exist but to update the data if it does exist. It can operate on entire sets of data rather than just on single rows and can perform alternate actions such as deletes.

MERGE
It is a common requirement to need to update data if it already exists but to insert it if it does not already exist. Some other database engines (not SQL Server) provide an UPSERT statement for this purpose. The MERGE statement provided by SQL Server is a more capable replacement for such statements in other database engines and is based on the ANSI SQL standard together with some Microsoft extensions to the standard. A typical situation where the need for the MERGE statement arises is in the population of data warehouses from data in source transactional systems. For example, consider a data warehouse holding details of a customer. When a customer row is received from the transactional system, it needs to be inserted into the data warehouse. When later updates to the customer are made, the data warehouse would then need to be updated.

Atomicity
Where statements in other languages typically operate on single rows, the MERGE statement in SQL Server can operate on entire sets of data in a single statement execution. It is important to realize that the MERGE statement functions as an atomic operation in that all inserts, updates or deletes occur or none occur.

Source and Target


The MERGE statement uses two table data sources. The target table is the table that is being modified and is specified first in the MERGE statement. Any inserts, updates or deletes are applied only to the target table.

Merging Data and Passing Tables

10-5

The source table provides the rows that need to be matched to the rows in the target table. You can think of the source table as the incoming data. It is specified in a USING clause. The source table does not have to be an actual table but can be other types of expressions that return a table such as: A view A sub-select (or derived table) with an alias A common table expression (CTE) A VALUES clause with an alias

The source and target are matched together as the result of an ON clause. This can involve one or more columns from both tables.

10-6

Implementing a Microsoft SQL Server 2008 R2 Database

WHEN MATCHED

Key Points
The WHEN MATCHED clause defines the action to be taken when a row in the source is matched to a row in the target.

WHEN MATCHED
The ON clause is used to match source rows to target rows. The WHEN MATCHED clause specifies the action that needs to occur when a source row matches a target row. In most cases, this will involve an UPDATE statement but it could alternately involve a DELETE statement. In the example shown in the slide, rows in the EmployeeUpdate table are being matched to rows in the Employee table based upon the EmployeeID. When a source row matches a target row, the FullName and EmploymentStatus columns in the target table are updated with the values of those columns in the source. Note that only the target table can be updated. If an attempt is made to modify any other table, a syntax error is returned.

Multiple Clauses
It is also possible to include two WHEN MATCHED clauses such as shown in the following code block:
WHEN MATCHED AND s.Quantity > 0 ... WHEN MATCHED ...

No more than two WHEN MATCHED clauses can be present. When two clauses are used, the first clause must have an AND condition. If the source row matches the target and also satisfies the AND condition, then the action specified in the first WHEN MATCHED clause is performed. Otherwise, if the source row

Merging Data and Passing Tables

10-7

matches the target but does not satisfy the AND condition, the condition in the second WHEN MATCHED clause is evaluated instead. When two WHEN MATCHED clauses are present, one action must specify an UPDATE and the other action must specify a DELETE. Question: What is different about the UPDATE statement in the example shown, compared to a normal UPDATE statement?

10-8

Implementing a Microsoft SQL Server 2008 R2 Database

WHEN NOT MATCHED BY TARGET

Key Points
The WHEN NOT MATCHED BY TARGET clause specifies the action that needs to be taken when a row in the source cannot be matched to a row in the target.

WHEN NOT MATCHED


The next clause in the MERGE statement that you will consider is the WHEN NOT MATCHED BY TARGET statement. It was mentioned in the last topic that the most common action performed by a WHEN MATCHED clause is to update the existing row in the target table. The most common action performed by a WHEN NOT MATCHED BY TARGET clause is to insert a new row into the target table. In the example shown in the slide, when a row from the EmployeeUpdate table cannot be found in the Employee table, a new employee row would be added into the Employee table. With a standard INSERT statement in T-SQL, the inclusion of a column list is considered a best practice and avoids issues related to changes to the underlying table such as the reordering of columns or the addition of new columns. The same recommendation applies to an INSERT action within a MERGE statement. While a column list is optional, best practice suggests including one.

Syntax
The words BY TARGET are optional and are often omitted. The clause is then just written as WHEN NOT MATCHED. Note again that no table name is included in the action statement (INSERT statement) as modifications may only be made to the target table. The WHEN NOT MATCHED BY TARGET clause is part of the ANSI SQL standard.

Merging Data and Passing Tables

10-9

WHEN NOT MATCHED BY SOURCE

Key Points
The WHEN NOT MATCHED BY SOURCE statement is used to specify an action to be taken for rows in the target that were not matched by rows from the source.

WHEN NOT MATCHED BY SOURCE


While much less commonly used than the clauses discussed in the previous topics, you can also take an action for rows in the target that did not match any incoming rows from the source. Generally, this will involve deleting the unmatched rows in the target table but UPDATE actions are also permitted. Note the format of the DELETE statement in the example on the slide. At first glance, it might seem quite odd as it has no table or predicate specified. In this example, all rows in the Employee table that were not matched by an incoming source row from the EmployeeUpdate table would be deleted. Question: What would the DELETE statement look like if it only deleted rows where the date in a column called LastModifed were older than a year?

10-10

Implementing a Microsoft SQL Server 2008 R2 Database

OUTPUT Clause and $action

Key Points
The OUTPUT clause was added in SQL Server 2005 and allows the return of a set of rows when performing data modifications. In 2005, this applied to INSERT, DELETE and UPDATE. In SQL Server 2008 and later, this clause can also be used with the MERGE statement.

OUTPUT Clause
The OUTPUT clause was a useful addition to the INSERT, UPDATE and DELETE statements in SQL Server 2005. For example, consider the following code:
DELETE FROM HumanResources.Employee OUTPUT deleted.BusinessEntityID, deleted.NationalIDNumber WHERE ModifiedDate < DATEADD(YEAR,-10,SYSDATETIME());

In this example, employees are deleted when their rows have not been modified within the last ten years. As part of this modification, a set of rows is returned that provides details of the BusinessEntityID and NationalIDNumber for each row deleted. As well as returning rows to the client application, the OUTPUT clause can include an INTO sub-clause that causes the rows to be inserted into another existing table instead. Consider the following example:
DELETE FROM HumanResources.Employee OUTPUT deleted.BusinessEntityID, deleted.NationalIDNumber INTO Audit.EmployeeDelete WHERE ModifiedDate < DATEADD(YEAR,-10,SYSDATETIME());

In this example, details of the employees being deleted are inserted into the Audit.EmployeeDelete table instead of being returned to the client.

Merging Data and Passing Tables

10-11

OUTPUT and MERGE


The OUTPUT clause can also be used with the MERGE statement. When an INSERT is performed, rows can be returned from the inserted virtual table. When a DELETE is performed, rows can be returned from the deleted virtual table. When an UPDATE is performed, values will be available in both the inserted and deleted virtual tables. Because a single MERGE statement can perform INSERT, UPDATE and DELETE actions, it can be useful to know which action was performed for each row returned by the OUTPUT clause. To make this possible, the OUTPUT clause also supports a $action virtual column that returns details of the action performed on each row. It returns the words "INSERT", "UPDATE" or "DELETE".

Composable SQL
In SQL Server 2008 and later, it is now possible to consume the rowset returned by the OUTPUT clause more directly. The rowset cannot be used as a general purpose table source but can be used as a table source for an INSERT SELECT statement. Consider the following example:
INSERT INTO Audit.EmployeeDelete SELECT Mods.EmployeeID FROM (MERGE INTO dbo.Employee AS e USING dbo.EmployeeUpdate AS eu ON e.EmployeeID = eu.EmployeeID WHEN MATCHED THEN UPDATE SET e.FullName = eu.FullName, e.EmploymentStatus = eu.EmploymentStatus WHEN NOT MATCHED THEN INSERT (EmployeeID,FullName,EmploymentStatus) VALUES (eu.EmployeeID,eu.FullName,eu.EmploymentStatus) OUTPUT $action AS Action,deleted.EmployeeID) AS Mods WHERE Mods.Action = 'DELETE';

In this example, the OUTPUT clause is being used with the MERGE statement. A row would be returned for each row either updated or deleted. However, you wish to only audit the deletion. You can treat the MERGE statement with an OUTPUT clause as a table source for an INSERT SELECT statement. The enclosed statement must be given an alias. In this case, the alias "Mods" has been assigned. The power of being able to SELECT from a MERGE statement is that you can then apply a WHERE clause. In this example, only the DELETE actions have been selected. Note that from SQL Server 2008 onwards, this level of query composability also applies to the OUTPUT clause when used in standard T-SQL INSERT, UPDATE and DELETE statements. Question: How could the OUTPUT clause be useful in a DELETE statement?

10-12

Implementing a Microsoft SQL Server 2008 R2 Database

MERGE Determinism and Performance

Key Points
The actions performed by a MERGE statement are not identical to those that would be performed by separate INSERT, UPDATE or DELETE statements.

Determinism
When an UPDATE statement is executed with a join, if more than one source row matches a target row, no error is thrown. This is not permitted for an UPDATE action performed within a MERGE statement. Each source row must match only a single target row or none at all. If more than a single source row matches a target row, an error occurs and all actions performed by the MERGE statement are rolled back.

Performance of MERGE
The MERGE statement will often outperform code constructed from separate INSERT, UPDATE and DELETE statements and conditional logic. In particular, the MERGE statement only ever makes a single pass through the data.

Merging Data and Passing Tables

10-13

Demonstration 1A: MERGE Statement

Key Points
In this demonstration you will see: How to use the MERGE statement How to use the OUTPUT clause with the MERGE statement How to perform optional updates with MERGE How to use MERGE as a composable query How to use the VALUES clause as a MERGE source

Demonstration Steps
1. 2. Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, click SQL Server Management Studio. In the Connect to Server window, type Proseware in the Server name text box and click Connect. From the File menu, click Open, click Project/Solution, navigate to D:\6232B_Labs\6232B_10_PRJ\6232B_10_PRJ.ssmssln and click Open. Open and execute the 00 Setup.sql script file from within Solution Explorer. Open the 11 Demonstration 1A.sql script file. Follow the instructions contained within the comments of the script file. Question: What is meant by the term "composable query"?

3. 4. 5.

10-14

Implementing a Microsoft SQL Server 2008 R2 Database

Lesson 2

Implementing Table Types

It was mentioned earlier that reducing the number of calls between client applications and SQL Server is important. The aim is to minimize the amount of time lost through network delays and latency. SQL Server 2000 introduced the TABLE data type for use as variables. SQL Server 2008 introduced the ability to declare these as permanent (or temporary) data types and to use them as parameters. The use of TABLE valued parameters can significantly reduce the number of round trips needed between client application code and SQL Server.

Objectives
After completing this lesson, you will be able to: Explain the need to reduce round-trip overhead Describe previous options for passing lists as parameters Explain the role of the TABLE type Populate TABLE types with row constructors

Merging Data and Passing Tables

10-15

Reducing Round-Trip Overhead

Key Points
In many applications, the time taken for commands to be sent to the server and for responses to be received can be substantial. It can often be longer than the time to execute the SQL command at the server. It is desirable then to minimize the number of times this happens in an operation.

Causes of Excessive Round Trips


Developers often aim to create code that is able to be reused. One common end result of this is the creation of many small functions and procedures that perform single tasks. Performing a larger task however, can then require calling many subtasks. Consider what is involved in inserting a new customer order into a SQL Server database. You typically need to do the following: Start a transaction Save the order header Save the first order detail line Save the second order detail line Save the third order detail line Commit the transaction

This means that performing a single action results in six separate round trips to the server.

Transaction Duration
A golden rule when designing systems to maximize concurrency is to never hold a transaction open for longer than required. In the previous example, the transaction is being held open for the time to insert the order header and detail lines. While the transaction needs to be held open for this time, its duration is being artificially increased by the time taken to make all the round trips to the server. This is not desirable. Question: How could the number of round trips being made to the server be reduced?

10-16

Implementing a Microsoft SQL Server 2008 R2 Database

Options for Passing Lists as Parameters

Key Points
One method for reducing the number of round trips from a client application to SQL Server is to pass lists of values in each trip.

Previous Options
Prior to SQL Server 2008, the available options for passing lists of values within a single procedure call were very limited. The most commonly used method was to use delimited lists. Mostly these were implemented as comma-delimited lists but other delimiters (eg: pipe) were used. When delimited lists were used, the entire set of values was sent as a string. There are issues with doing this: No control was able to be exerted over the data type being passed. A string could be passed to code expecting a number. The structure was loose. For example, one string might contain five columns and another might contain six. Custom string parsing logic needed to be written.

Passing XML
Another option for passing lists of values was to use XML. This became more common with SQL Server 2005 when the XML data type was introduced. Prior to SQL Server 2005, developers would also sometimes pass XML values as strings but they then needed to write very complex parsing logic. With the introduction of the XML data type, the parsing became easier but not trivial. Processing the received XML is also non-trivial and some processing methods (such as OPENXML) had memory implications, while others (such as the nodes() method) had query optimization implications. In modules 17 and 18 you will learn more about the use of XML in SQL Server.

Merging Data and Passing Tables

10-17

Demonstration 2A: Passing Delimited Lists

Key Points
In this demonstration you will see: How to query a table-valued function that performs list parsing How the function allows for different delimiters How to use the function in a join How common errors can occur with delimited lists

Demonstration Steps
1. If Demonstration 1A was not performed: Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, click SQL Server Management Studio. In the Connect to Server window, type Proseware in the Server name text box and click Connect. From the File menu, click Open, click Project/Solution, navigate to D:\6232B_Labs\6232B_10_PRJ\6232B_10_PRJ.ssmssln and click Open. Open and execute the 00 Setup.sql script file from within Solution Explorer.

2. 3.

Open the 21 Demonstration 2A.sql script file. Follow the instructions contained within the comments of the script file.

Question: What are the basic problems with using delimited lists for parameters?

10-18

Implementing a Microsoft SQL Server 2008 R2 Database

Introduction to the TABLE Type

Key Points
SQL Server 2008 introduced the ability to create user TABLE data types and record them in the system catalog. These types are very useful as they can be used for both variables and for parameters.

TABLE Type
In SQL Server 2000, it was possible to declare a variable of type TABLE. You needed to define the schema of the table when declaring the variable such as in the following code:
DECLARE @BalanceList TABLE (CustomerID int, CurrentBalance decimal(18,2));

In this example, a variable called @BalanceList is defined as being a table. The schema of the table and the variable, only last for the duration of the batch in which the variable is defined. SQL Server 2008 introduced the ability to create user-defined table data type definitions. You can create table data types that can be used both for the data type of variables but also for the data type of parameters. In the example shown on the slide, CustomerBalance is declared as a new data type. You can declare a variable as being of CustomerBalance data type as follows:
CREATE TYPE dbo.CustomerBalance AS TABLE (CustomerID int, CurrentBalance decimal(18,2)); GO DECLARE @BalanceList dbo.CustomerBalance;

Merging Data and Passing Tables

10-19

A key advantage of table data types is that you can pass complex structures inside a table more easily than you could in alternatives such as comma-delimited lists. You can have multiple rows each of two or more columns and you can be sure of the data types that will be stored. This is also useful even when declaring variables as a table type can be created and then used for variables through the database application, which leads to less potential inconsistencies. Note that there is no ALTER TYPE statement that can be used to modify the TABLE type definition. Types must be dropped and then recreated when they need to be altered.

10-20

Implementing a Microsoft SQL Server 2008 R2 Database

Populating TABLE Types with Row Constructors

Key Points
SQL Server 2008 also introduced the concept of row constructors and multi-row INSERT statements. These are useful when working with TABLE data types as well as when working with database tables.

Row Constructors for Populating TABLE Types


Versions of SQL Server prior to SQL Server 2008 only permitted inserting a single row of data at a time with an INSERT statement unless an INSERTSELECT or INSERT...EXEC statement was used. SQL Server 2008 introduced the concept of a row constructor. In the example shown in the slide, a variable named @Balance of type dbo.CustomerBalance has been declared. That data type was the table data type that was defined in the example from the previous topic. Three rows have then been inserted into the table variable. Note that a multi-row INSERT that inserts 3 rows is quite different to 3 separate INSERT statements. It is an atomic operation involving 3 rows in that all inserts occur or none occur. Note also that multi-row INSERT statements cannot include more than 1000 rows per statement and that multi-row INSERTS also help reduce the number of roundtrips from a client application to a server. Question: What would improve the INSERT query shown in the slide example?

Merging Data and Passing Tables

10-21

Demonstration 2B: TABLE Types and Row Constructors

Key Points
In this demonstration you will see: 1. 2. 3. 1. How to work with row constructors How to declare a table data type How to work with variables with user-defined table data types If Demonstration 1A was not performed: Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, click SQL Server Management Studio. In the Connect to Server window, type Proseware in the Server name text box and click Connect. From the File menu, click Open, click Project/Solution, navigate to D:\6232B_Labs\6232B_10_PRJ\6232B_10_PRJ.ssmssln and click Open. Open and execute the 00 Setup.sql script file from within Solution Explorer.

Demonstration Steps

2. 3.

Open the 22 Demonstration 2B.sql script file. Follow the instructions contained within the comments of the script file.

Question: Can other users make use of the table type that you create?

10-22

Implementing a Microsoft SQL Server 2008 R2 Database

Lesson 3

Using TABLE Types As Parameters

In the previous lesson you saw how to declare TABLE data types and how to declare variables of those types. Another potential use for the TABLE data types is in the declaration of parameters, particularly for use with stored procedures but also able to be used with user-defined functions. In this lesson, you will see how to use TABLE input parameters to stored procedures and see how this solves the round trip problems identified in lesson 1. You will also see how to call a stored procedure when passing a table valued parameter.

Objectives
After completing this lesson, you will be able to: Describe the use of TABLE input parameters for stored procedures Use row constructors to populate parameters to be passed to stored procedures

Merging Data and Passing Tables

10-23

TABLE Input Parameters for Stored Procedures

Key Points
As well as being used for declaring variables, user-defined table data types can be used as parameter data types for stored procedures and functions. (User-defined functions will be discussed in Module 13).

Table Valued Parameters


Table-valued parameters can only be used as input parameters. Note that the term READONLY must be specified and that it is the only allowable value. In the example shown in the slide, a data type called SalesDetails is being created to hold the detail lines for a customer sale. A stored procedure is then being created that takes sales header details as standard relational parameters but also takes the entire list of sales details rows as a single parameter. This allows for the creation of a stored procedure that would process an entire sale in a single call.

Reducing Round Trips


In an earlier discussion, the requirements for saving a customer order were noted. Using this same technique, you could place the order header in one table and all the order rows in another table and pass both in a single call to a stored procedure that saves the order. That single stored procedure could also begin and commit the transaction so the transaction would not span even a single network round trip. What is more interesting though is that you could pass multiple order headers and their corresponding order detail rows in a single call. This means that the procedure could now save one or more orders with all their detail rows in a single round-trip to the server. Question: What would you have to do to be able to pass multiple sales and their detail lines in a single call?

10-24

Implementing a Microsoft SQL Server 2008 R2 Database

Using Row Constructors to Populate Parameters

Key Points
In the previous topic, you saw how to declare a stored procedure that uses a table-valued parameter. The final step in using such a procedure is to then pass a table parameter in the EXEC statement.

Passing a Table Valued Parameter in an EXEC Statement


As well as defining a table-valued parameter for a stored procedure, you also need to construct a table to pass to the stored procedure in the EXEC call. First, you declare a table variable with the same user-defined table data type that was used when declaring the stored procedure. Next, you populate that variable. Row constructors are ideal for populating the table variables that will be passed in an EXEC call. In the example shown in the slide, three product detail rows are being inserted into the @SalesDetails variable. Finally, the stored procedure is called via an EXEC statement and the detail rows are passed as a single parameter. You will see this in detail in the upcoming demonstration.

Merging Data and Passing Tables

10-25

Demonstration 3A: Passing Tables to Stored Procedures

Key Points
In this demonstration you will see: 1. 2. 3. 4. How traditional stored procedure calls often involve multiple round trips to the server How to declare a table data type How to use the table data type to avoid round trips How to view catalog information about the table data types by querying the sys.types and sys.table_types system views

Demonstration Steps
1. If Demonstration 1A was not performed: Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, click SQL Server Management Studio. In the Connect to Server window, type Proseware in the Server name text box and click Connect. From the File menu, click Open, click Project/Solution, navigate to D:\6232B_Labs\6232B_10_PRJ\6232B_10_PRJ.ssmssln and click Open. Open and execute the 00 Setup.sql script file from within Solution Explorer.

2. 3.

Open the 31 Demonstration 3A.sql script file. Follow the instructions contained within the comments of the script file.

Question: What is the purpose of the SCOPE_IDENTITY() function shown in the demonstration?

10-26

Implementing a Microsoft SQL Server 2008 R2 Database

Lab 10: Passing Tables and Merging Data

Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.

In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.

5. 6. 7.

In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User. Log on using the following credentials:

Merging Data and Passing Tables

10-27

i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd 8. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 9. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_10_PRJ\6232B_10_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.

Lab Scenario
In earlier versions of SQL Server, passing lists of values to stored procedures was a challenge. SQL Server 2008 introduced the table type and table-valued parameters. In this lab, you will create a replacement stored procedure Reports.GetProductsByColorList_Test that uses a table-valued parameter to replace an existing stored procedure Reports.GetProductsByColorList that was based on passing a comma-delimited list of values. If time permits, you will then create a new procedure that processes complete rows of data and performs updates using the MERGE statement.

Supporting Documentation
Procedure Required: Marketing.SalespersonMerge Requirements Input Parameters: Table of Salesperson details, including SalespersonID, FirstName, MiddleName, LastName, BadgeNumber, EmailAlias, SalesTerritoryID. The parameter should be named: SalespersonDetails None For each row, return one column called Action that contains INSERT or UPDATE and another column with the SalespersonID. The SalespersonID must be provided. If it matches an existing salesperson, that row should be updated. Only update columns that are provided. Any SalesTerritoryID that is provided must be valid as it is defined as a foreign key to the Marketing.SalesTerritory table.

Output Parameters: Output Rows:

Notes:

10-28

Implementing a Microsoft SQL Server 2008 R2 Database

Exercise 1: Create a Table Type


Scenario
In this exercise, you will create a table type to support the parameter that will later need to be passed to the replacement stored procedure. The main tasks for this exercise are as follows: 1. 2. 3. Review the parameters of a stored procedure Review the existing function Create a new table type

Task 1: Review the parameters of a stored procedure


Review the parameters of the existing stored procedure Reports.GetProductsByColorList

Task 2: Review the existing function


Review the function dbo.StringListToTable used by the existing stored procedure. Note the hardcoded length of 1000 for each component of the returned table entries

Task 3: Create a new table type


Create a new table type to support this type of input parameter. Call the type StringList Results: After this exercise, you have created a new table type.

Merging Data and Passing Tables

10-29

Exercise 2: Use a Table Type Parameter


Scenario
In this exercise, you will create a replacement stored procedure Reports.GetProductsByColorList_Test that uses the table type for its parameter. The main tasks for this exercise are as follows: 1. 2. Create the stored procedure Test the stored procedure

Task 1: Create the stored procedure


Create a new stored procedure that is functionally equivalent to Reports.GetProductsByColorList except that the new procedure (call it Reports.GetProductsByColorList_Test) takes a single table @ColorList as a parameter

Task 2: Test the new procedure


Test the new procedure Results: After this exercise, you should have created a new stored procedure that uses the table type for its parameter.

10-30

Implementing a Microsoft SQL Server 2008 R2 Database

Challenge Exercise 3: Use a Table Type with MERGE (Only if time permits)
Scenario
In this exercise, you will create a new stored procedure that takes a table-valued parameter and uses the MERGE statement to update a table in the marketing system. The procedure should allow for the creation or update of salespeople held in the Marketing.Salesperson table. The main tasks for this exercise are as follows: 1. 2. 3. Create a new table type Create a replacement procedure Test the replacement procedure.

Task 1: Create a new table type


Create the required table type. (Create it in the dbo schema)

Task 2: Create a replacement stored procedure


Review the supporting documentation and create a replacement procedure based on the requirements

Task 3: Test the replacement procedure


Test the replacement procedure Results: After this exercise, you should have created a new stored procedure that takes a table-valued parameter and uses the MERGE statement to update a table.

Merging Data and Passing Tables

10-31

Module Review and Takeaways

Review Questions
1. 2. What is the difference between SOURCE NOT MATCHED and TARGET NOT MATCHED in a MERGE statement? What is a key advantage of the MERGE statement in terms of performance?

Best Practices
1. 2. Use multi-row inserts when the rows being inserted are related in some way, for example, the detail rows of an invoice. Consider making multiple-entity procedures instead of single-entity procedures to help minimize round trip behavior and to reduce locking. For example, very minor changes are required to construct a stored procedure that can insert multiple sales orders compared to a stored procedure that can insert a single sales order.

Vous aimerez peut-être aussi