在SQL存储过程中将DECLARE分成两部分有什么好处?

时间:2015-02-21 00:11:34

标签: tsql stored-procedures azure-sql-database

我在存储过程中看到过这样的代码:

DECLARE @Var1 NVARCHAR (64),
        @var2 NVARCHAR (64),
        @Var3 NVARCHAR(512);

DECLARE @Var4 AS INT,
        @Var5 AS INT,
        @Var6 AS INT,
        @Var7 nvarchar(32);

以这种方式声明它们有什么好处,而不是将它们全部放在一个DECLARE语句中,如下所示?

DECLARE @Var1 NVARCHAR (64),
        @var2 NVARCHAR (64),
        @Var3 NVARCHAR(512),
        @Var4 AS INT,
        @Var5 AS INT,
        @Var6 AS INT,
        @Var7 nvarchar(32);

1 个答案:

答案 0 :(得分:1)

像提到的T I这样的可读性可能是最重要的一个。使用初始化器时可能存在优点和缺点。使用先前声明的变量的值必须在单独的语句中。仅当应用初始化程序时,以下两个选项之间存在很大的性能差异。选项A的运行速度是原来的两倍。

选项A

DECLARE @i INT = 0;
DECLARE @time DATETIME2(7) = SYSDATETIME();
WHILE @i < 10000000
BEGIN
    DECLARE @A CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
          , @B CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
          , @C CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
          , @D CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
          , @E CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
          , @F CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
          , @G CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
          , @H CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
          , @J CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
          , @K CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
          , @L CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS';

    SET @i += 1;
END
PRINT DATEDIFF(ms, @time, SYSDATETIME());

选项B

DECLARE @i INT = 0;
DECLARE @time DATETIME2(7) = SYSDATETIME();
WHILE @i < 10000000
BEGIN
    DECLARE @A CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
    DECLARE @B CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
    DECLARE @C CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
    DECLARE @D CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
    DECLARE @E CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
    DECLARE @F CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
    DECLARE @G CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
    DECLARE @H CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
    DECLARE @J CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
    DECLARE @K CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS'
    DECLARE @L CHAR(1000) = 'ASDGASDGASGDSAGSADGASGS';

    SET @i += 1;
END
PRINT DATEDIFF(ms, @time, SYSDATETIME());