SQL Server, How to remove updates elements from User-Defined Table Type?

社会主义新天地 提交于 2019-12-13 16:13:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!