简体   繁体   中英

MERGE Self-Join SQL Server

I am using the MERGE command on SQL Server 2008, to insert/update a row in the table. However the target and source tables are the same. So I want to verify if the row is present update it in the same table, or else insert it. HOwever, I am unable to achieve the insert using the following script.

Could you anyone please point out what is going wrong ?

   `MERGE INTO Table1 as t
    USING (SELECT * FROM Table1 WHERE ConsumerId = @ConsumerId AND Table1Id = @Table1Id) AS s
    ON (t.ConsumerId = s.ConsumerId
    AND t.Table1Id = s.Table1Id) 
    WHEN MATCHED THEN
        UPDATE SET
            VersionNumber = s.VersionNumber + 1
    WHEN NOT MATCHED THEN
        INSERT (
            ConsumerId,
            Table1Id,
            VersionNumber
            )
        VALUES (
            @ConsumerId,
            @Table1Id,
            1
            );

Runnig this says : 0 rows affected.

If necessary UPDATE/INSERT statement then the Source table should always contain values. Put your variables as source table and change in the UPDATE statement SET VersionNumber on VersionNumber += 1 OR t.VersionNumber = t.VersionNumber + 1

MERGE INTO Table1 as t
USING (
       SELECT @ConsumerId AS ConsumerId, 
              @Table1Id AS Table1Id, 
              1 AS VersionNumber
       ) AS s
ON (t.ConsumerId = s.ConsumerId AND t.Table1Id = s.Table1Id) 
WHEN MATCHED THEN
  UPDATE 
    SET VersionNumber += 1
WHEN NOT MATCHED THEN
    INSERT (
            ConsumerId,
            Table1Id,
            VersionNumber
            )
    VALUES (
            s.ConsumerId,
            s.Table1Id,
            s.VersionNumber
            );

Demo on SQLFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM