开发者

Is it possible to use the Sql MERGE syntax to UPDATE / INSERT data from another variable TABLE?

I wish to Insert or Update a row in a table - so I wish to try and use the MERGE syntax. My problem is that my data (to insert/update) exists in a variable table. I'm not sure how to write the correct syntax for the insert/update part.

Here's my pseduo code :-

-- Here's the Variable Table开发者_如何学Go ... 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, ????, ?????, ????)

.. and I'm not sure how I make sure the UPDATE correctly only updates 1 row (ie... does that need a WHERE clause?)

Finally, I based my this post on this SO question.


Yes it's possible. Your syntax was off though. The below seems to work. I have kept @PersonId as a separate scalar variable outside the table variable as that's how you have it in your question. And I have assumed that the Primary Key of SomeTable is 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜