当我想要SQL舍入时,哪一个很快(Round,Module(%),Floor)?

时间:2017-03-15 03:24:24

标签: sql-server tsql

我需要将值向上舍入到最近的5.有几种方法可以做到这一点。只是想知道哪一个很快。是否有任何影响使这段代码更慢

DECLARE @number int = 104

SELECT (ROUND( @number / 5,0 ) * 5 ) + 5    -- 1
SELECT CEILING( @number / 5.0 ) * 5     -- 2
SELECT ((@number/5)*5) + 5              -- 3

DECLARE @remainder int                  -- 4
SET @remainder = ( @number % 5);

IF @remainder = 0
    SELECT @number
ELSE
    SELECT @number -  @remainder + 5

1 个答案:

答案 0 :(得分:0)

实际上很容易为自己测试它:

declare @number int = 104

declare @cnt int, @res int
declare @t1 datetime2(7), @t2 datetime2(7), @diff1 int, @diff2 int

set @cnt = 0
set @t1 = sysdatetime()
while @cnt < 1000000 begin
    set @cnt = @cnt+1
end
set @t2 = sysdatetime()
set @diff1 = datediff(ms, @t1, @t2)

set @cnt = 0
set @t1 = sysdatetime()
while @cnt < 1000000 begin
    set @res = (round( @number / 5,0 ) * 5 ) + 5    -- 1
    set @cnt = @cnt+1
end
set @t2 = sysdatetime()
set @diff2 = datediff(ms, @t1, @t2)
select @diff2-@diff1

对所有四种情况执行此操作,多次以消除边缘结果,并进行比较。

剧透:1和3似乎是最快的,持续时间几乎相同,2稍慢,4是最慢的。