SSIS加快工作日计算查询

时间:2015-02-27 13:32:58

标签: sql performance function ssis

对于db中的每一行,我需要计算2天之间的工作日数。所以我创建了一个函数,它接受2个日期参数,连接到日期维度并计算输入时间段之间的工作日数。这很好,期望它非常慢,因为它必须为每一行进行计算。

比较一下,如果我从表中选择随机列(不包括cycleTime计算),那么速度在几秒钟内就会有100万行。 如果我包含使用sql函数的CycleTime计算,则速度为每10秒15k行。对于100万行,它总共大约10分钟。

这是查询

SELECT 
CycleTime = 
    CASE WHEN DateStarted is not null and DateCompleted is not null
    THEN DM.dbo.ufnCalculateWorkingDays(DateStarted, DateCompleted)
    ELSE NULL 
    END
from MyTable

功能:

CREATE FUNCTION [dbo].[ufnCalculateWorkingDays]
(
    @StartDate date,
    @EndDate date
)
RETURNS int
AS
BEGIN

    DECLARE @WorkingDays int;

    WITH CTE AS 
    (   
        select WorkingDay = Date 
        from DimDate
        where 
        Date between @StartDate and @EndDate
        AND IsHolidayUSA = 0
        AND IsWeekday = 1
    )

    Select @WorkingDays = COUNT(*) from CTE 

    RETURN @WorkingDays;
END

还有其他方法可以加快查询速度吗?

1 个答案:

答案 0 :(得分:2)

这样的事情怎么样? (显然无法进行性能测试,因为我没有你的数据库):

WITH cte AS (
 SELECT [Date] AS WorkingDay,
 ROW_NUMBER() OVER (ORDER BY [Date] ASC) AS RN
 FROM DimDate
 WHERE IsHolidayUSA = 0
 AND IsWeekday = 1
)
SELECT
 DateStarted,
 DateCompleted,
 c2.RN - c1.RN AS CycleTime
FROM MyTable t
INNER JOIN cte c1
 ON t.DateStarted=c1.WorkingDay
INNER JOIN cte c2
 ON t.DateCompleted=c2.WorkingDay

如果DateStarted和DateCompleted都包含在同一个索引中,它应该非常快。