这行得通,
- 声明一个名为 @isinsert 的标志变量(位)
- 将其初始化为 1。
- 在更新子句中将其设置为 0。
像这样:(假设一个名为 table1 的表带有一个数字 'id' 字段和一个 nvarchar 'field1' 字段)。
declare @id numeric(18,0) -- That's the he lookup key
set @id=999 -- We use id as the search key
-- You can use any other field
declare @field nvarchar(50)
set @field = 'insert or update value(s)' -- This is the new value
declare @isinsert bit -- This is a flag that will
set @isinsert=1 -- indicate whether an insert or
-- an update were performed
MERGE table1 AS target
USING (SELECT @field) AS source (field1)
ON (target.id = @id)
WHEN MATCHED THEN
UPDATE SET field1 = source.field1
,@isinsert = 0 -- Set @isinsert to 0 on updates
WHEN NOT MATCHED THEN
INSERT (field1)
VALUES (source.field1);
if (@isinsert=1) print concat('inserted record at id: ',@@IDENTITY)
else print concat('updated record at id: ',@id)