【问题标题】:What has better performance on SQL Server什么在 SQL Server 上有更好的性能
【发布时间】:2011-04-11 10:12:44
【问题描述】:

我想将多个值(最多十个)与返回最小值的函数进行比较。

我的同事写了这样的函数:

set @smallest = null

if @smallest is null or @date0 < @smallest 
begin
    set @smallest = @date0
end

if @smallest is null or @date1 < @smallest 
begin
    set @smallest = @date1
end
... (repeating 10 times)

除此之外,if 语句可以写得更聪明(第一次比较后空检查可能会消失)我想知道创建一个内存索引表并让函数返回第一个值会更有效吗? 有没有我可以阅读的文档?

【问题讨论】:

  • 当前信息是如何存储的?你可以运行 MIN() 吗?
  • 不,这些是数据行中的单独字段。目前比较了三个值,但该方法目前最多支持 10 个。

标签: sql-server performance function stored-procedures


【解决方案1】:

创建内存索引表

在 10 条记录上建立索引是没有意义的。创建一个派生表(将位于内存中),如下所示,然后跨表运行 MIN:

select @smallest = MIN(Adate)
from (
    select @date0 Adate union all
    select @date1 union all
    select @date2 union all
    -- ....
    select @date9) X

【讨论】:

  • 我喜欢这种方法,但性能是否优于 10 个 IF 语句?
  • 应该没有显着差异。如果连续执行 100 次左右,可能需要 1 毫秒或 2 毫秒,即使这样,我也不确定哪个会更快。
猜你喜欢
  • 2011-01-27
  • 1970-01-01
  • 1970-01-01
  • 2014-08-02
  • 1970-01-01
  • 2010-10-06
  • 1970-01-01
  • 1970-01-01
  • 2012-08-18
相关资源
最近更新 更多