方法1:先查询,根据查询结果判断使用insert或者update IF EXISTS (SELECT 1 FROM table_A WHERE Id = @Id) BEGIN UPDATE dbo.table_A SET Value = @Value WHERE Id = @Id; END ELSE BEGIN INSERT INTO dbo.table_A (Id, Value) VALUES(@Id, @Value) END 方法2:先更新,根据更新结果影响的条目数判断是否需要插入 UPDATE dbo.table_A SET Value = @Value WHERE Id = @Id; IF(@@ROWCOUNT = 0) BEGIN INSERT INTO dbo.table_A (Id, Value) VALUES(@Id, @Value) END 方法3:使用MERGE语句,将待upsert的数据作为source,merge到目标表 MERGE INTO table_A as T USING (SELECT @Id AS id, @Value AS value ) AS S ON T.Id = S.id WHEN MATCHED THEN UPDATE SET T.Value = S.value WHEN NOT MATCHED THEN INSERT(Id, Value) VALUES(S.id, S.value);
标签:BEGIN,dbo,SqlServer,Value,插入,value,table,Id,UpSert From: https://www.cnblogs.com/wzf-Learning/p/16730047.html