可以使用SQL Server来模拟MYSQL功能的DUPLICATE KEY UPDATE

前端之家收集整理的这篇文章主要介绍了可以使用SQL Server来模拟MYSQL功能的DUPLICATE KEY UPDATE前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用sql Server 2008,并希望能够利用像 MySQL的ON DUPLICATE KEY UPDATE子句之类的INSERT语句

当前的遗留代码执行一个删除和后续插入,它与单独线程中的重复键插入运行并发问题:

这是我在生产环境中看到的错误

  1. Violation of PRIMARY KEY constraint 'PK_Audience'. Cannot insert duplicate key in object 'dbo.Audience'.

(sp_ContentUpdate)

首要的关键:

  1. AudienceId,VersionId

违规sql

  1. DELETE FROM dbo.Audience
  2. WHERE VersionId = @VersionId
  3.  
  4. IF @AudienceXml IS NOT NULL
  5. BEGIN
  6. INSERT INTO dbo.Audience (
  7. VersionId,AudienceId,CreatedDate,CreatedByPersonId,)
  8. SELECT @VersionId,GETUTCDATE(),@PersonId
  9. FROM dbo.Audience
  10. JOIN @AudienceXml.nodes('/Audiences/Audience') node(c)
  11. ON Audience.AudienceName = c.value('@Name','nvarchar(50)')
  12. END

将此Tsql包含在事务中似乎可以通过更改时序来删除并发问题或掩盖问题.但是,我不认为在事务中包装实际上已经解决了并发问题.

也许我这个错了.您的建议不胜感激

解决方法

那么,比尔打败了我们,但这里是一个可能的样子:
  1. Merge dbo.Audience As target
  2. Using (
  3. Select @VersionId As VersionId,GetUtcDate() As CreatedDate,@PersonId As CreatedByPersonId
  4. From dbo.Audience
  5. Join @AudienceXml.nodes('/Audiences/Audience') node(c)
  6. On Audience.AudienceName = c.value('@Name','nvarchar(50)')
  7. )
  8. When Matched Then
  9. Update
  10. Set VersoinId = target.VersionId,Audience = target.AudienceId,CreatedDate = target.CreatedDate,CreatedByPersionId = target.CreatedByPersonId
  11. When Not Matched Then
  12. Insert dbo.Audience(VersionId,CreatedByPersonId)

猜你在找的MsSQL相关文章