如何使用MERGE或Upsert Sql语句

时间:2018-05-08 11:33:48

标签: sql sql-server merge sql-update upsert

如何使用MERGE Sql语句或UPDATE语句作为我的下面的代码。我有一个名为MachineName的columnName,其他列值更改但MachineName不会更改。如果列MachineName发生更改,则需要在secondrow中插入新值。如果不是我需要更新同一行。我怎样才能做到这一点。这是一种正确的方法吗?请帮忙

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);

2 个答案:

答案 0 :(得分:1)

您可以在Temporary表中加载新的Machine数据,然后可以使用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);

答案 1 :(得分:0)

过去,我成功地“选择”了要向上插入MERGE命令的USING部分的值:

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