在存储过程或函数或触发器中何时需要创建变量有助于性能优化? 哪一个比下面哪个更好或两者都有相同的表现?
选项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
答案 0 :(得分:1)
docs对变量不太具体,除了说一旦声明它通过该批处理过程可用:
变量的范围从声明它的位置延迟到声明它的批处理或存储过程的结束。
我的假设将在以后声明它更好(假设他们如何说出文档) - 如果你不使用它,请避免声明它。 然而,真正的答案是测试并分析它。无论哪种方法在练习中效果更好都是真正的解决方案,恕我直言。
我也希望这不是一个不成熟的优化。如果您需要声明命令以使脚本运行得更快,那么您可能正在寻找错误的位置。