1. You can assign values directly when defining variables
DECLARE @Id int = 5
2.Insert statements can insert multiple rows of data at once
INSERT into StateList VALUES (@Id, ' WA '), (@Id + 1, ' FL '), (@Id + 2, ' NY ')
3. Support + = operator
SET Stateid + = 1
The output function in SQL Server 2005 can return the contents of both insert,update and delete, and the output in 2008 also has this function. Here's how to use the new T-SQL statement merge combination of output with 2008:
Create the following table:
[C-sharp]View Plaincopy
- CREATE TABLE Book (
- ISBN varchar (PRIMARY KEY),
- Price Decimal,
- Shelf int)
- CREATE TABLE Weeklychange (
- ISBN varchar (PRIMARY KEY),
- Price Decimal,
- Shelf int)
- CREATE TABLE Bookhistory (
- Action nvarchar (10),
- NEWISBN varchar (20),
- Newprice Decimal,
- newshelf int,
- OLDISBN varchar (20),
- Oldprice Decimal,
- oldshelf int,
- Archivedat datetime2)
The SQL statement is
[C-sharp]View Plaincopy
- 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 isn't matched then
- INSERT VALUES (WC. ISBN, WC. Price, WC. Shelf)
- OUTPUT $action, inserted.*, deleted.*, Sysdatetime ()
- into Bookhistory;
The result set is:
SELECT * from Bookhistory
GO
Action newisbn newprice newshelf oldisbn oldprice oldshelf archivedat
------ ------- -------- -------- ------- -------- -------- ---------------------------
UPDATE a 101 1 a 100 1 2007-11-25 14:47:23.9907552
INSERT C 3 null NULL NULL 2007-11-25 14:47:23.9907552
There are two output cases of INSERT and update. If you only need one of these, you can filter it in the following way:
[C-sharp]View Plaincopy
- INSERT into book (ISBN, Price, Shelf, Archivedat)
- SELECT ISBN, Price, Shelf, GETDATE () from
- (MERGE book as B
- USING Weeklychange as WC
- On B.ISBN = WC. ISBN and B.archivedat is NULL
- When matched and (B.price <> WC. Price OR b.shelf <> WC. Shelf) Then
- UPDATE SET price = WC. Price, Shelf = WC. Shelf
- When isn't matched then
- INSERT VALUES (WC. ISBN, WC. Price, WC. Shelf, NULL)
- OUTPUT $action, WC. ISBN, Deleted.price, deleted.shelf
- ) Changes (Action, ISBN, Price, Shelf)
- WHERE Action = ' UPDATE ';
SQL Server 2008 New T-SQL shorthand syntax