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