实体框架6.1.3 exec sp_executesql导致巨大的性能问题

时间:2016-07-03 01:36:37

标签: sql-server performance entity-framework

对于SQL Server数据库,我有一个非常基本的实体框架查询,它非常慢(2条记录为30秒)。我与DBA合作,以便在数据库上执行实际查询:

exec sp_executesql N'SELECT 
    [Project1].[DocumentID] AS [DocumentID], 
    [Project1].[CreationDate] AS [CreationDate], 
    [Project1].[DocType] AS [DocType]
    FROM ( SELECT 
        [Extent1].[DocumentID] AS [DocumentID], 
        [Extent1].[DocType] AS [DocType], 
        [Extent1].[CreationDate] AS [CreationDate]
        FROM   [dbo].[DocFile] AS [Extent1]
        LEFT OUTER JOIN [dbo].[Demographics] AS [Extent2] ON [Extent1].[DemographicsKey] = [Extent2].[DemographicsKey]
        LEFT OUTER JOIN [dbo].[Client] AS [Extent3] ON [Extent1].[ClientKey] = [Extent3].[ClientKey]
        WHERE (([Extent1].[DocType] = @p__linq__0) OR (([Extent1].[DocType] IS NULL) AND (@p__linq__0 IS NULL))) AND ([Extent1].[CreationDate] >= @p__linq__1) AND (([Extent2].[SSN] = @p__linq__2) OR (([Extent2].[SSN] IS NULL) AND (@p__linq__2 IS NULL))) AND (([Extent3].[ControlNumber] = @p__linq__3) OR (([Extent3].[ControlNumber] IS NULL) AND (@p__linq__3 IS NULL)))
    )  AS [Project1]
    ORDER BY [Project1].[CreationDate] DESC',N'@p__linq__0 nvarchar(4000),@p__linq__1 datetime2(7),@p__linq__2 nvarchar(4000),@p__linq__3 nvarchar(4000)',@p__linq__0=N'AST',@p__linq__1='2013-07-01 15:52:25.4288579',@p__linq__2=N'818760001',@p__linq__3=N'8187600002'

当我从SQL Server Management Studio运行这个确切的查询时,它也需要大约30秒。

但是,当我取出exec sp_executesql并用内联值替换变量时,查询只需几毫秒:

SELECT 
    [Project1].[DocumentID] AS [DocumentID], 
    [Project1].[CreationDate] AS [CreationDate], 
    [Project1].[DocType] AS [DocType]
    FROM ( SELECT 
        [Extent1].[DocumentID] AS [DocumentID], 
        [Extent1].[DocType] AS [DocType], 
        [Extent1].[CreationDate] AS [CreationDate]
        FROM   [dbo].[DocFile] AS [Extent1]
        LEFT OUTER JOIN [dbo].[Demographics] AS [Extent2] ON [Extent1].[DemographicsKey] = [Extent2].[DemographicsKey]
        LEFT OUTER JOIN [dbo].[Client] AS [Extent3] ON [Extent1].[ClientKey] = [Extent3].[ClientKey]
        WHERE (([Extent1].[DocType] = 'AST') OR (([Extent1].[DocType] IS NULL) AND ('AST' IS NULL))) AND ([Extent1].[CreationDate] >= '7/1/2013') AND (([Extent2].[SSN] = '818760002') OR (([Extent2].[SSN] IS NULL) AND ('818760002' IS NULL))) AND (([Extent3].[ControlNumber] = '8187600002') OR (([Extent3].[ControlNumber] IS NULL) AND ('8187600002' IS NULL)))
    )  AS [Project1]

为什么这两个查询的性能会有如此显着的差异?如何修复EF代码或修复数据库以使代码执行速度更快?

谢谢!

1 个答案:

答案 0 :(得分:1)

所以看起来正确的解决方案在这里:Entity Framework query slow, but same SQL in SqlQuery is fast

很可能是类型匹配的问题(如可空类型或varchar与nvarchar等)。

如果它可以帮助您解决问题,那将很高兴。 ;)

相关问题