views:

29

answers:

1

Hi folks,

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 ... 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.

+1  A: 

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);
Martin Smith
Cheers Martin. I'll give this a go on Mon when I get back to the office. It does make sence, when I read your answer :) Kick ass! Thanks!
Pure.Krome
Perfect! works like a charm. Cheers :)
Pure.Krome