0

在存储过程或函数或触发器中根据需要创建变量是否有助于性能优化?下面哪个更好或两者具有相同的性能?

选项1:

CREATE TRIGGER [dbo].[UpdateAmount] ON [RequestDB].[dbo].[Invoice]
AFTER UPDATE
AS
BEGIN
 IF UPDATE(Service_Amount)
 BEGIN
  DECLARE @NewService_Amount float,@OldService_Amount float //Var Created When needed
  SELECT @NewService_Amount = I.Service_Amount FROM INSERTED I
  SELECT @OldService_Amount = D.Service_Amount FROM DELETED D   
  IF (@NewService_Amount <> @OldService_Amount)
  BEGIN
   SELECT @InvId = I.Id FROM INSERTED I 
   DECLARE @DiffService_Amount float //Var Created When needed
   SET @DiffService_Amount = @NewService_Amount - @OldService_Amount
   UPDATE [RequestDB].[dbo].[Request] SET Actual_Amount = @DiffService_Amount WHERE Invoice_Id = @InvId
  END
 END
END

选项 2:

CREATE TRIGGER [dbo].[UpdateAmount] ON [RequestDB].[dbo].[Invoice]
AFTER UPDATE
AS
BEGIN
 DECLARE @NewService_Amount float,@OldService_Amount float.@DiffService_Amount float //All Var Created at once on top of code
 IF UPDATE(Service_Amount)
 BEGIN
  SELECT @NewService_Amount = I.Service_Amount FROM INSERTED I /*For New UPDATE Value: INSERTED. For Old BEFORE UPDATE Valie: DELETED*/
  SELECT @OldService_Amount = D.Service_Amount FROM DELETED D   
  IF (@NewService_Amount <> @OldService_Amount)
  BEGIN
   SELECT @InvId = I.Id FROM INSERTED I 
   SET @DiffService_Amount = @NewService_Amount - @OldService_Amount
   UPDATE [RequestDB].[dbo].[Request] SET Actual_Amount = @DiffService_Amount WHERE Invoice_Id = @InvId
  END
 END
END
4

1 回答 1

1

文档对变量并没有太具体,只是说一旦声明它就可以通过该批处理过程获得:

变量的范围从声明它的那一刻开始一直持续到声明它的批处理或存储过程结束。

我的假设是稍后声明它会更好(考虑到他们如何使用文档)——如果你不使用它,请避免声明它。然而,真正的答案是对其进行测试和分析。恕我直言,在实践中效果更好的将是真正的解决方案。

我也希望这不是过早的优化。如果您想通过声明顺序来使您的脚本运行得更快,那么您可能找错地方了。

于 2013-04-15T13:43:46.313 回答