问题
I have a User-Defined Table Type, lets say @TT dbo.IntType readonly,
IntType is batch of int
, as Primary-Key
CREATE TYPE [dbo].[IntType] AS TABLE(
[T] [int] NOT NULL,
PRIMARY KEY CLUSTERED
I like to do UPDATE
based on all key(int
) in IntType
, and INSERT
new rows for the key(int
) not exist in the database (an upsert)
I wonder if theres a easy way to remove the "UPDATED" key(int
)? Then I can insert the rest.
(or if you have a super one-line upsert for SQL Server 2010!!!)
回答1:
Use the MERGE
statement.
http://technet.microsoft.com/en-us/library/bb510625.aspx
Let me see if I can put something together.
EDIT: Example
MERGE INTO [TargetTable] AS T
USING (SELECT l.T AS 'id' FROM @list l ) AS S
ON (T.[id] = S.[id])
WHEN MATCHED THEN
UPDATE SET
T.updated = 1
WHEN NOT MATCHED THEN
INSERT VALUES ([insert value into each column of target table]);
EDIT 2: The parameter @list
is the list that is passed in that you populated with the ids
来源:https://stackoverflow.com/questions/9779915/sql-server-how-to-remove-updates-elements-from-user-defined-table-type