我需要在项目中插入/更新项目并返回记录的ID。这是我的T-SQL:
BEGIN
MERGE [AgentDumps] WITH (HOLDLOCK) AS Target
USING (SELECT @AgentID) AS Source (AgentID)
ON (target.AgentID = source.AgentID)
WHEN MATCHED THEN
UPDATE
Set DumpData = @DumpData,
UpdateTime = getdate()
WHEN NOT MATCHED THEN
INSERT
([AgentID],
[DumpData]
)
VALUES
(
@AgentID,
@DumpData
);
SELECT CAST(scope_identity() AS int)
END
仅在插入新记录时才有效。但是如果更新现有的查询,则返回null。我尝试在Update命令中添加OUTPUT INSERTED.ID:
BEGIN
MERGE [AgentDumps] WITH (HOLDLOCK) AS Target
USING (SELECT @AgentID) AS Source (AgentID)
ON (target.AgentID = source.AgentID)
WHEN MATCHED THEN
UPDATE
Set DumpData = @DumpData,
UpdateTime = getdate()
OUTPUT INSERTED.ID
WHEN NOT MATCHED THEN
INSERT
([AgentID],
[DumpData]
)
VALUES
(
@AgentID,
@DumpData
);
SELECT CAST(scope_identity() AS int)
END
但SQL返回:关键字'WHEN'附近的语法不正确。