programming4us
         
 
 
SQL Server

SQL Server 2012 : T-SQL Enhancements - The INSERT OVER DML Syntax (part 1) - A Filterable Alternative to OUTPUT…INTO

- How To Install Windows Server 2012 On VirtualBox
- How To Bypass Torrent Connection Blocking By Your ISP
- How To Install Actual Facebook App On Kindle Fire
7/13/2013 7:45:46 PM

The MERGE statement supports the OUTPUT clause to access the INSERTED and DELETED pseudo-tables, as well as a special $action string value that returns ‘INSERT’, ‘UPDATE’, or ‘DELETE’ according to the action performed for each row processed by the merge operation.

The results generated by the OUTPUT clause can be captured in another table or table variable using OUTPUT…INTO, making it possible to easily maintain historical records of changes in the database. However, because using OUTPUT…INTO dumps every row captured by the clause into the destination table or table variable, it is not possible to filter on this data.

1. A Filterable Alternative to OUTPUT…INTO

INSERT OVER DML refers to a special syntax in which you wrap an INSERT INTO…SELECT statement around any data manipulation language (DML) statement (INSERT, UPDATE, DELETE, or MERGE) that has an OUTPUT clause, rather than using OUTPUT…INTO on the DML statement itself. The subtle but crucial difference here is that OUTPUT…INTO captures the changes, while the INSERT OVER DML syntax consumes the changes captured by OUTPUT. By treating the OUTPUT changes as the source for a standard INSERT INTO…SELECT statement, you can apply any WHERE clause to the INSERT INTO…SELECT statement that you want.

Beyond that, there isn’t anything more you can do with INSERT OVER DML than what you can with OUTPUT…INTO. But to casually overlook the significance of filtering change data is to miss the point of INSERT OVER DML entirely. By being able to filter change data with a WHERE clause, you can better control which data changes captured are shipped to the destination table and which aren’t. The benefits of this capability are best realized with an example.

In this scenario, you are maintaining an audit of all changes that are posted from one table to another. You have a master list of book prices and shelf locations in the Book table where each book is identified by its ISBN number. Every week, you receive a new table named WeeklyChanges that contains updates to the book data, also keyed by ISBN number. In addition to price and shelf changes for existing books, the weekly update table can also include new books. You learned already that MERGE can handle this scenario (it was made to, in fact), and can effectively apply the appropriate updates and inserts from the WeeklyChanges table to the Book table by joining on ISBN and using the WHEN MATCHED and WHEN NOT MATCHED clauses. You also know that the OUTPUT…INTO clause can be used to capture and store all data changes performed by the merge into a history table. To work through the scenario, start first by using OUTPUT…INTO to dump these changes to the BookHistory table. Then you’ll modify the approach to use INSERT OVER DML instead, and gain better control of the change data archival process.

Create the Book and WeeklyChange tables as shown in Example 1.

Example 1. Creating the Book and WeeklyChange tables.

CREATE TABLE Book(
  ISBN varchar(20) PRIMARY KEY,
  Price decimal,
  Shelf int)

CREATE TABLE WeeklyChange(
  ISBN varchar(20) PRIMARY KEY,
  Price decimal,
  Shelf int)

Next, create the BookHistory table. This will be the recipient of the changes captured by the OUTPUT INTO clause of the MERGE statement, as shown in Example 2.

Example 2. Creating the BookHistory table.

CREATE TABLE BookHistory(
  Action nvarchar(10),
  NewISBN varchar(20),
  NewPrice decimal,
  NewShelf int,
  OldISBN varchar(20),
  OldPrice decimal,
  OldShelf int,
  ArchivedAt datetime2)

Now create the uspUpdateBooks stored procedure to perform the weekly update merge operation. The stored procedure records all data changes to the BookHistory table, as shown in Example 3.

Example 3. Using OUTPUT…INTO with MERGE.

CREATE PROCEDURE uspUpdateBooks AS
 BEGIN

  MERGE Book AS B
   USING WeeklyChange AS WC
    ON B.ISBN = WC.ISBN
   WHEN MATCHED AND (B.Price <> WC.Price OR B.Shelf <> WC.Shelf) THEN
    UPDATE SET B.Price = WC.Price, B.Shelf = WC.Shelf
   WHEN NOT MATCHED THEN
    INSERT VALUES(WC.ISBN, WC.Price, WC.Shelf)
   OUTPUT $action, inserted.*, deleted.*, SYSDATETIME()
    INTO BookHistory;

 END

This code should require no detailed explanation, as we just covered MERGE thoroughly in the previous section. What’s different here, however, is the OUTPUT…INTO clause. This clause records the action, new values, old values, and current server date and time in the BookHistory table, from the $action virtual column, INSERTED pseudo-table columns, DELETED pseudo-table columns, and SYSDATETIME function. (In this particular scenario, $action can return only the string ‘INSERT’ or ‘UPDATE’, because deletions are not being processed.)

Now populate the Book and WeeklyChange tables to set the stage for the update, as shown here:

INSERT INTO Book VALUES('A', 100, 1)
INSERT INTO Book VALUES('B', 200, 2)
INSERT INTO WeeklyChange VALUES('A', 101, 1)
INSERT INTO WeeklyChange VALUES('C', 300, 3)

The WeeklyChange table shows a change in price for book A from $100 to $101 and also adds a new book C priced at $300 on shelf 3. When you run the uspUpdateBooks stored procedure, those two operations take place as you’d expect. This is confirmed by the number of rows affected message, as shown here:

EXEC uspUpdateBooks
GO

(2 row(s) affected)

In addition, the actions and data changes made by those insert and update operations (and the dates and times that they occurred) have been saved to the BookHistory table as the result of the OUTPUT…INTO clause, as shown here:

SELECT * FROM BookHistory
GO

Action NewISBN NewPrice NewShelf OldISBN OldPrice OldShelf ArchivedAt
------ ------- -------- -------- ------- -------- -------- ---------------------------
UPDATE A       101      1        A       100      1        2012-02-25 14:47:23.9907552
INSERT C       300      3        NULL    NULL     NULL     2012-02-25 14:47:23.9907552

So far, so good, right? Until, after further consideration, you realize that most of your operations will be inserts, and there will be very few updates. Thus, an unacceptable amount of storage is going to be required for capturing the inserts that have no old values and that therefore don’t provide any meaningful historical value beyond the creation date and time (which you could store in the Book table if you wanted to). Given that every book must be inserted but most books are not typically updated, the result will be a disproportionate amount of inserts over updates in the BookHistory table. That’s a lot of storage to hold duplicate data that has little or no value. Unfortunately, there’s simply no way to filter out the inserts and save just the updates using OUTPUT…INTO. In our revised scenario, you are interested in capturing only updates without inserts. This requires filtering, and INSERT OVER DML provides the solution.

You will use INSERT OVER DML in the next example, and—just to keep things interesting—the historical data will be appended to the Book table itself, rather than being stored to a separate history table. In the revised example, there is an ArchivedAt column in the Book table that contains the server date and time for history records added when books are updated. Thus, a NULL in this column identifies the rows holding the current values, whereas all other rows with non-NULL values in the ArchivedAt column represent previous values in history rows.

Start like you did the last time by creating the tables, as shown in Example 4.

Example 4. Creating new versions of the Book and WeeklyChange tables for use with INSERT OVER DML.

-- Cleanup from previous example
DROP TABLE Book
DROP TABLE WeeklyChange
DROP TABLE BookHistory
DROP PROCEDURE uspUpdateBooks
GO

CREATE TABLE Book(
  ISBN varchar(20),
  Price decimal,
  Shelf int,
  ArchivedAt datetime2)

CREATE UNIQUE CLUSTERED INDEX UI_Book ON Book(ISBN, ArchivedAt)

CREATE TABLE WeeklyChange(
  ISBN varchar(20) PRIMARY KEY,
  Price decimal,
  Shelf int)

Notice this time that a unique index is created on the combined ISBN and ArchivedAt columns. A primary key cannot be created on just the ISBN column as before, because the Book table will now contain multiple records with the same ISBN number (because the table holds historical change data as well as current data). Only one row per ISBN number will have a NULL value in the ArchivedAt column, which is the row that contains the current values for a book. All other rows with the same ISBN number will have non-NULL values in ArchivedAt, which serves as the time stamp of a previous update and will contain the historical values archived for that book at that time. By ensuring uniqueness between both ISBN and ArchivedAt, you are guaranteed that only one current row for each book is ever stored in the Book table, because the table will not tolerate two rows with the same ISBN numbers and NULL values for ArchivedAt.


Other -----------------
- SQL Server 2012 : T-SQL Enhancements - The MERGE Statement (part 2)
- SQL Server 2012 : T-SQL Enhancements - The MERGE Statement (part 1)
- Configuring SQL Server 2008 : Memory configuration (part 2) - Setting minimum and maximum memory values
- Configuring SQL Server 2008 : Memory configuration (part 1) - 32-bit memory management
- SQL server 2012 : T-SQL Enhancements - Date and Time Data Types (part 2) - Date and Time Functions
- SQL server 2012 : T-SQL Enhancements - Date and Time Data Types (part 1) - Date and Time Accuracy, Storage, and Format
- SQL server 2012 : T-SQL Enhancements - Table-Valued Parameters (part 2)
- SQL server 2012 : T-SQL Enhancements - Table-Valued Parameters (part 1)
- SQL Server 2008 R2 : Database Files and Filegroups (part 2)
- SQL Server 2008 R2 : Database Files and Filegroups (part 1)
- Installing SQL Server 2012 : The Installation Process (part 4) - Post Installation Tasks
- Installing SQL Server 2012 : The Installation Process (part 3) - Installing SQL Server 2012 Through the Command Line, Installing SQL Server 2012 Through PowerShell
- Installing SQL Server 2012 : The Installation Process (part 2) - Installing SQL Server 2012 Through the Installation Center
- Installing SQL Server 2012 : The Installation Process (part 1) - SQL Server 2012 Installation Center
- Installing SQL Server 2012 : Preparing the Server, Selecting the Edition
- SQL Server 2012 : SQL Server Architecture - SQL SERVER’S EXECUTION MODEL AND THE SQLOS
- SQL Server 2012 : SQL Server Architecture - THE LIFE CYCLE OF A QUERY (part 3) - A Simple Update Query
- SQL Server 2012 : SQL Server Architecture - THE LIFE CYCLE OF A QUERY (part 2) - Plan Cache
- SQL Server 2012 : SQL Server Architecture - THE LIFE CYCLE OF A QUERY (part 1)
- Protecting SQL Server Data : CELL-LEVEL ENCRYPTION - Views and Stored Procedures (part 2) - Creating the Stored Procedures
 
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
programming4us programming4us
Video Tutorail Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Biztalk Exchange Server Microsoft LynC Server Microsoft Dynamic Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 Adobe Indesign Adobe Flash Professional Dreamweaver Adobe Illustrator Adobe After Effects Adobe Photoshop Adobe Fireworks Adobe Flash Catalyst Corel Painter X CorelDRAW X5 CorelDraw 10 QuarkXPress 8 windows Phone 7 windows Phone 8 BlackBerry Android Ipad Iphone iOS
Celebrity Style, Fashion Trends, Beauty and Makeup Tips.