Compare performance difference of T-SQL Between and '<' '>' operator?

后端 未结 7 1227
情歌与酒
情歌与酒 2020-12-31 05:02

I\'ve tried searching through search engines,MSDN,etc. but can\'t anything. Sorry if this has been asked before. Is there any performance difference between using the T-SQL

7条回答
  •  耶瑟儿~
    2020-12-31 05:42

    I was also interested in whether there is a performance difference when I used (>= and <=) compared to using the between keyword. (I come from a dotnet background and like the >= style operators).
    Here is the script I used:

    DECLARE
        @Startdatetime datetime ,
        @Diff int = 0 ,
        @Addrowcount int = 1000;
    
    SET NOCOUNT ON;
    
    --Create a tempory table to perform our tests on
    
    CREATE TABLE dbo.perftest( id smallint NOT NULL
                                           IDENTITY(1 , 1)
                                           PRIMARY KEY ,
                               mytext nvarchar( 50 )NOT NULL );
    
    --Now add some sample rows
    
    SET @Addrowcount = 1000;
    
    WHILE(@Addrowcount > 0)
    
        BEGIN
    
            INSERT INTO dbo.perftest( mytext )
            VALUES( 'thetext' );
    
            SET @Addrowcount = @Addrowcount - 1;
    
        END;
    
    SELECT @Startdatetime = GETDATE();
    
    -- do method 1 here
    
    SELECT mytext
      FROM dbo.perftest
      WHERE(id >= 100)
       AND (id <= 900);
    
    --end method1
    
    SELECT @Diff = DATEDIFF( millisecond , @Startdatetime , GETDATE());
    
    PRINT ':Method 1: ' + CAST(@Diff AS nvarchar( 20 )) + ' ms';
    
    --reset start time
    
    SELECT @Startdatetime = GETDATE();
    
    --do method2 here
    
    SELECT mytext
      FROM dbo.perftest
      WHERE id BETWEEN 100
        AND 900;
    
    --end method2
    
    SELECT @Diff = DATEDIFF( millisecond , @Startdatetime , GETDATE());
    
    PRINT ':Method 2: ' + CAST(@Diff AS nvarchar( 20 )) + ' ms';
    

    The results were:

    Method 1: 140 ms

    Method 2: 70 ms

    So it appears that performance is improved by using between.

提交回复
热议问题