SQL 重复键错误 - 删除行并创建新行与更新行

SQL duplicate key error - delete row and create new row vs. update row

我正在使用 Azure SQL 并且有一个客户端服务,每 30 分钟记录一次用户的位置和数据。它将此数据从客户端上传到数据库,但出现错误。

我有这个存储过程:

INSERT INTO ThisIsMyTable(UserID, Latitude, Longitude)
VALUES (@UserID, @Latitude, @Longitude)

但是当同一个用户的客户端使用相同的 UserID 上传数据时,我收到以下错误:

Violation of PRIMARY KEY constraint 'PrimaryKey_asdad'. Cannot insert duplicate key in object 'dbo.ThisIsMyTable'. The duplicate key value is (TheUsersUserID). The statement has been terminated.

如何更改存储过程并检查密钥是否已存在,如果存在 - 更新 lat/lon.. 或者删除该行并创建一个新行会更好吗?

尼尔斯

MERGE INTO ThisIsMyTable AS Target
USING (VALUES (@UserID,@Latitude, @Longitude)
       AS Source (UserID, Lat, Long)
ON Target.UserID = Source.UserID
WHEN MATCHED THEN
UPDATE SET Latitude = Source.Lat, Longitude=Source.Long
WHEN NOT MATCHED BY TARGET THEN
INSERT (UserID, Latitude, Longitude) VALUES (UserID, Lat, Long)
if exists (select 1 from ThisIsMyTable where UserID = @UserID)

   update ThisIsMyTable 
   set latitude = @latitude, longitude = @longitude 
   where UserID = @UserID

else

   INSERT INTO ThisIsMyTable (UserID, Latitude, Longitude)
   VALUES (@UserID, @Latitude, @Longitude)

您可以在 SQL 中合并语句,更多详细信息在这里:https://msdn.microsoft.com/en-us/library/bb510625.aspx