SQL Merge语句 - 输出到标量变量(SQL Server)

时间:2015-09-08 16:45:03

标签: sql sql-server

我正在考虑SQL服务器中的MERGE语句。我通常使用它来插入/更新单行,我意识到这不是唯一的用途,但这似乎是我经常做的事情。

但是,如果要插入值1,或者更新以增加值并输出递增的值,会发生什么情况,例如:

CREATE TABLE [Counter] (
  [Key] VARCHAR(255) NOT NULL PRIMARY KEY,
  [Value] INT NOT NULL
);

DECLARE @paramKey VARCHAR(255);

SET @paramKey = 'String';

MERGE [Counter] AS targt
USING (Values(@paramKey)) AS source ([Key])
ON (targt.[Key] = source.[Key])
WHEN MATCHED THEN 
    UPDATE SET Value = Value +1
WHEN NOT MATCHED THEN
    INSERT ([Key], Value)
    VALUES (source.[Key], 1);

-- but now I want the new value!

有没有办法做到这一点?我注意到https://msdn.microsoft.com/en-gb/library/bb510625.aspx中的输出子句,但它似乎不适用于标量(我可以输出到单个行表变量,但这似乎是错误的):

-- using table variables but seems 
DECLARE @paramKey VARCHAR(255), @value int;

SET @paramKey = 'String'

DECLARE @Tab table (
    [Value] INT
)

MERGE Counter AS targt
USING (Values(@paramKey)) AS source ([Key])
ON (targt.[Key] = source.[Key])
WHEN MATCHED THEN 
    UPDATE SET Value = Value +1
WHEN NOT MATCHED THEN
    INSERT ([Key], Value)
    VALUES (source.[Key], 1)
    OUTPUT inserted.[Value] INTO @Tab;

-- can now use @Tab as a single rowed table variable

有更好的选择吗?

0 个答案:

没有答案