如何将3个更新合并为一个

时间:2016-10-25 15:41:28

标签: sql sql-server tsql

我有3次更新

UPDATE [Person]
SET [Email] = @Prefix
WHERE [Id] = @PersonId AND ISNULL([Email], '') <> ''

UPDATE [Person]
SET [Phone] = @Phone
WHERE [Id] = @PersonId AND ISNULL([Phone], '') <> ''

UPDATE [Person]
SET [Skype] = @Skype
WHERE [Id] = @PersonId AND ISNULL([Skype], '') <> ''

我可以将它组合成一个或如何编写更多性能操作?感谢

2 个答案:

答案 0 :(得分:5)

我的意思是,你可以将它们结合起来:

UPDATE [Person]
SET [Email] = CASE WHEN ISNULL([Email], '') <> '' THEN @Prefix ELSE [Email] END,
    [Phone] = CASE WHEN ISNULL([Phone], '') <> '' THEN @Phone ELSE [Phone] END,
    [Skype] = CASE WHEN ISNULL([Skype], '') <> '' THEN @Skype ELSE [Skype] END
WHERE [Id] = @PersonId 
AND (ISNULL([Email], '') <> '' OR ISNULL([Phone], '') <> '' OR ISNULL([Skype], '') <> '');

不确定这是否会实际改善性能

答案 1 :(得分:2)

试一试。但是,如果只有一个新值,它将覆盖其他两个值。

UPDATE [Person]
SET [Email] = CASE WHEN ISNULL([Email], '') <> '' THEN @Prefix ELSE [Email] END,
SET [Phone] = CASE WHEN ISNULL([Phone], '') <> '' THEN @Phone ELSE [Phone] END,
SET [Skype] = CASE WHEN ISNULL([Skype], '') <> '' THEN @Skype ELSE [Skype] END
WHERE [Id] = @PersonId 
AND (ISNULL([Email], '') <> ''
OR ISNULL([Phone], '') <> ''
OR ISNULL([Skype], '') <> '')