更大的结果集MSSQL的性能问题

时间:2016-07-26 08:15:22

标签: sql-server performance tsql stored-procedures

我目前在MSSQL中有一个存储过程,我根据我给存储过程的变量多次执行SELECT语句。存储过程计算用户可以启用的每个过滤器将返回多少结果。 存储过程不是问题,我将select语句从te存储过程转换为常规select语句,如下所示:

DECLARE @contentRootId int = 900589
DECLARE @RealtorIdList varchar(2000) = ';880;884;1000;881;885;'
DECLARE @publishSoldOrRentedSinceDate int = 8
DECLARE @isForSale BIT= 1
DECLARE @isForRent BIT= 0   
DECLARE @isResidential BIT= 1   
--...(another 55 variables)...

--Table to be returned
DECLARE @resultTable TABLE
(
    variableName varchar(100),
    [value] varchar(200)
)

-- Create table based of inputvariable. Example: turns ';18;118;' to a table containing two ints 18 AND 118 
DECLARE @RealtorIdTable table(RealtorId int) 
INSERT INTO @RealtorIdTable SELECT * FROM dbo.Split(@RealtorIdList,';') option (maxrecursion 150)

INSERT INTO @resultTable ([value], variableName) 
SELECT [Value], VariableName FROM( 
    Select count(*) as TotalCount, 
        ISNULL(SUM(CASE WHEN reps.ForRecreation = 1 THEN 1 else 0 end), 0) as ForRecreation,
        ISNULL(SUM(CASE WHEN reps.IsQualifiedForSeniors = 1 THEN 1 else 0 end), 0) as IsQualifiedForSeniors,
        --...(A whole bunch more SUM(CASE)...
    FROM TABLE1 reps
    LEFT JOIN temp t on
            t.ContentRootID = @contentRootId 
            AND t.RealEstatePropertyID = reps.ID
        WHERE 
            (EXISTS(select 1 from @RealtorIdTable where RealtorId = reps.RealtorID))
            AND (@SelectedGroupIds IS NULL OR EXISTS(select 1 from @SelectedGroupIdtable where GroupId = t.RealEstatePropertyGroupID))
            AND (ISNULL(reps.IsForSale,0) = ISNULL(@isForSale,0)) 
            AND (ISNULL(reps.IsForRent, 0) = ISNULL(@isForRent,0)) 
            AND (ISNULL(reps.IsResidential, 0) = ISNULL(@isResidential,0))  
            AND (ISNULL(reps.IsCommercial, 0) = ISNULL(@isCommercial,0))  
            AND (ISNULL(reps.IsInvestment, 0) = ISNULL(@isInvestment,0))  
            AND (ISNULL(reps.IsAgricultural, 0) = ISNULL(@isAgricultural,0))
            --...(Around 50 more of these WHERE-statements)...
            ) as tbl

    UNPIVOT ( 
        [Value]
        FOR [VariableName] IN(
        [TotalCount],
        [ForRecreation],
        [IsQualifiedForSeniors],
        --...(All the other things i selected in above query)...
        )
    ) as d

    select * from @resultTable

Realtor和contentID的组合为我提供了一组默认的X记录量。当我选择一个给我约4600条记录的组合时,执行时间约为250毫秒。当我用一个组合执行sattement时,给我约600条记录,执行时间约为20ms。

我想知道为什么会这样。我尝试删除所有SUM(选择中的CASE,我尝试从WHERE子句中删除几乎所有内容,我尝试删除JOIN。但我一直看到结果集4600和600之间的巨大差异。

1 个答案:

答案 0 :(得分:1)

当记录数量很大时,表变量的性能会更差。请考虑使用临时表。见When should I use a table variable vs temporary table in sql server?

另外,请考虑使用替代SQL代码替换UNPIVOT。编写自己的TSQL代码将为您提供更多控制,甚至可以提高性能。请参阅示例PIVOT, UNPIVOT and performance