0

我希望InsertUpdate表中的一行 - 所以我希望尝试使用MERGE语法。我的问题是我的数据(插入/更新)存在于variable table. 我不确定如何为插入/更新部分编写正确的语法。

这是我的伪代码:-

-- Here's the Variable Table ... and not it has not PK.
DECLARE @PersonId INTEGER

DECLARE @variableTable TABLE (
    @SomeScore DECIMAL(10,7),
    @SomeAverage DECIMAL(10,7),
    @SomeCount INTEGER)

-- Insert or Update
MERGE INTO SomeTable
WHERE PersonId = @PersonId
WHEN MATCHED THEN
    UPDATE
    SET PersonScore = ??????????
        PersonAverage = ???????
        PersonCount = ????????
WHEN NOT MATCHED THEN
    INSERT(PersonId, PersonScore, PersonAverage, PersonCount)
    VALUES(@PersonId, ????, ?????, ????)

..而且我不确定如何确保UPDATE正确地只更新 1 行(即……这需要一个WHERE子句吗?)

最后,我的这篇文章基于这个 SO question

4

1 回答 1

1

是的,这是可能的。不过,您的语法已关闭。下面似乎工作。我@PersonId在表变量之外保留了一个单独的标量变量,因为这就是您在问题中的方式。我假设 SomeTable 的主键是PersonId

DECLARE @PersonId INT

DECLARE @variableTable TABLE (
    SomeScore DECIMAL(10,7),
    SomeAverage DECIMAL(10,7),
    SomeCount INTEGER
    )

-- Insert or Update
MERGE SomeTable AS T
USING @variableTable AS S
ON (T.PersonId = @PersonId) 

WHEN MATCHED THEN
    UPDATE
    SET T.PersonScore = SomeScore,
        T.PersonAverage = SomeAverage,
        T.PersonCount = SomeCount
WHEN NOT MATCHED  BY TARGET THEN
    INSERT(PersonId, PersonScore, PersonAverage, PersonCount)
    VALUES(@PersonId, SomeScore, SomeAverage, SomeCount);
于 2010-06-25T07:20:12.777 回答