存储过程不使用索引

时间:2015-04-17 15:52:14

标签: sql sql-server tsql stored-procedures indexing

此存储过程是linq查询执行的结果:我是从Sql Server Profiler获取的

exec sp_executesql N'SELECT 
[Limit1].[C2] AS [C1], 
[Limit1].[object] AS [object], 
[Limit1].[C1] AS [C2]
FROM ( SELECT TOP (50) 
    [GroupBy1].[A1] AS [C1], 
    [GroupBy1].[K1] AS [object], 
    1 AS [C2]
    FROM ( SELECT 
        [Extent1].[object] AS [K1], 
        COUNT(1) AS [A1]
        FROM [dbo].[BEM_EVT_FULL] AS [Extent1]
        WHERE [Extent1].[date] > @p__linq__0
        GROUP BY [Extent1].[object]
    )  AS [GroupBy1]
)  AS [Limit1]',N'@p__linq__0 datetime2(7)',@p__linq__0='2015-01-21 00:00:00'

我已经在所有列(对象和日期)上创建了索引。问题是这个查询完全忽略了索引,运行时间超过3分钟。

另一方面,我有这个查询,我手动运行。

SELECT 
[Limit1].[C2] AS [C1], 
[Limit1].[object] AS [object], 
[Limit1].[C1] AS [C2]
FROM ( SELECT TOP (50) 
    [GroupBy1].[A1] AS [C1], 
    [GroupBy1].[K1] AS [object], 
    1 AS [C2]
    FROM ( SELECT 
        [Extent1].[object] AS [K1], 
        COUNT(1) AS [A1]
        FROM [dbo].[BEM_EVT_FULL] AS [Extent1]
        WHERE [Extent1].[date] > convert(datetime2, '2015-01-21 00:00:00.0000000', 121)
        GROUP BY [Extent1].[object]
    )  AS [GroupBy1]
)  AS [Limit1]

此查询受益于索引并在1s下运行。有谁知道为什么会这样?

1 个答案:

答案 0 :(得分:0)

我觉得添加OPTION(RECOMPILE)会对你有所帮助。问题是你如何做实体框架。查看此链接Adding a query hint when calling Table-Valued Function

exec sp_executesql 
    N'SELECT    [Limit1].[C2] AS [C1], 
                [Limit1].[object] AS [object], 
                [Limit1].[C1] AS [C2]
    FROM 
    (
        SELECT TOP (50) [GroupBy1].[A1] AS [C1], 
                        [GroupBy1].[K1] AS [object], 
                        1 AS [C2]
        FROM 
        (
            SELECT 
            [Extent1].[object] AS [K1], 
            COUNT(1) AS [A1]
            FROM [dbo].[BEM_EVT_FULL] AS [Extent1]
            WHERE [Extent1].[date] > @p__linq__0
            GROUP BY [Extent1].[object]
        )  AS [GroupBy1]
    )  AS [Limit1]
    OPTION (RECOMPILE)',

    N'@p__linq__0 datetime2(7)',
    @p__linq__0='2015-01-21 00:00:00'