admin

如何使用MERGE或Upsert Sql语句

sql

我如何在下面的代码中使用MERGESql语句或UPDATE语句。我有一个称为columnName的MachineName列,其他列值更改了,但是MachineName却没有更改。如果列MachineName更改,则需要在第二行中插入新值。如果不是,我需要更新同一行。我怎样才能做到这一点。这是正确的方法吗?请帮忙

MERGE INTO [devLaserViso].[dbo].[Machine] WITH (HOLDLOCK) 
USING [devLaserViso].[dbo].[Machine] 
ON (MachineName = MachineName)
  WHEN MATCHED 
       THEN UPDATE SET MachineName = L1,ProgramName= ancdh.pgm, TotalCount= 10, RightCount=4, 
                       LeftCount= 3,ErrorCode=0,FinishingTime=fsefsefef
  WHEN NOT MATCHED 
       THEN INSERT (MachineName, ProgramName, TotalCount, RightCount, LeftCount, ErrorCode, FinishingTime) 
            VALUES (L02, djiwdn.pgm, 11, 5, 4, 0, dnwdnwoin);

阅读 247

收藏
2021-07-01

共1个答案

admin

您可以将新的Machine数据加载到Temporary表中,然后可以使用Merge语句来更新Machine表中已经存在记录的记录,如果Machine表中不存在新记录,则将插入新记录。

MERGE [devLaserViso].[dbo].[Machine] t WITH (HOLDLOCK) 
USING [devLaserViso].[dbo].[TempMachine] s
ON (s.MachineName = t.MachineName)
WHEN MATCHED THEN 
UPDATE SET t.MachineName = s.MachineName,t.ProgramName =s.ProgramName
WHEN NOT MATCHED BY TARGET THEN INSERT (MachineName,ProgramName) VALUES (s.MachineName, s.ProgramName);
2021-07-01