从Linq SQL Query比直接从Management Studio慢得多

时间:2013-05-27 13:51:32

标签: sql-server performance linq

通过C#Linq to SQL执行查询时,我遇到了一个非常奇怪的性能问题。通常,查询需要一两秒才能执行,但对于某些非常具体的搜索条件,查询突然需要一分多钟才能通过Linq to SQL运行,但在SQL Management Studio中仍然只需要2秒。

查询:

从Linq to SQL查找得到的查询是如下所示的相当复杂的结构。 TV_TRACKER_ORDER是一个合并来自10个以上表格的数据的视图。

DECLARE @p0 Int; SET @p0 = '4';
DECLARE @p1 Int; SET @p1 = '666685';
DECLARE @p2 DateTime; SET @p2 = '2/1/2013 12:00:00 AM';
DECLARE @p3 DateTime; SET @p3 = '5/23/2013 12:00:00 AM';

SELECT [t0].[HAULIER], [t0].[G_NUMBER], [t0].[CUST_ORDER_REF], [t0].[CUSTOMER], [t0].[RELEASE_NO], [t0].[BILL_OF_LADEN], [t0].[TERMINAL], [t0].[PRODUCT], [t0].[SCHEDULED_DELIVERY_DATE], [t0].[DRIVER], [t0].[TRACTOR], [t0].[TRAILER], [t0].[STATE], [t0].[DRIVER_NAME], [t0].[HOME_DEPOT], [t0].[TRACTOR_NAME], [t0].[TRAILER_NAME], [t0].[CUSTOMER_NAME], [t0].[TERMINAL_NAME], [t0].[STATE_NAME], [t0].[Shift], [t0].[SHIFT_NAME], [t0].[HOME_DEPOT_NAME], [t0].[DELIVERY_LOCATION], [t0].[DELIVERY_LOCATION_NAME], [t0].[SYSTEM_REMAINDER_RESOLUTION]
FROM [dbo].[TV_TRACKER_ORDER] AS [t0]
WHERE EXISTS(
    SELECT NULL AS [EMPTY]
    FROM (
        SELECT TOP (50) [t2].[G_NUMBER]
        FROM (
            SELECT DISTINCT [t1].[G_NUMBER]
            FROM [dbo].[TV_TRACKER_ORDER] AS [t1]
            WHERE ([t1].[STATE] = (CONVERT(Decimal(29,4),@p0))) AND ([t1].[HAULIER] = (CONVERT(Decimal(29,4),@p1))) AND ((@p2) <= [t1].[SCHEDULED_DELIVERY_DATE]) AND ([t1].[SCHEDULED_DELIVERY_DATE] <= (@p3))
            ) AS [t2]
        ORDER BY [t2].[G_NUMBER]
        ) AS [t3]
    WHERE [t3].[G_NUMBER] = [t0].[G_NUMBER]
    )
ORDER BY [t0].[G_NUMBER]

我尝试了什么:

  • 如果我将TOP 50更改为TOP 49或TOP 51,则查询只需几秒钟即可运行(没有TOP条目,查询将返回1841组中的10121行)。
  • 如果我将开始时间(@ p2)设置为一年前,查询也会在几秒钟内完成。
  • 使用SQL Server管理Studio Activity Monitor我可以看到错误的查询DO实际运行超过一分钟,我可以看到运行的SQL与我上面显示的相匹配。

帮助

我完全不知道如何处理这个问题。

  • 为什么查询在SQL Server Management Studio上运行得很快,但是通过Linq会非常慢?
  • 如果我从查询中提取更多记录(将TOP 50更改为TOP 51),它如何在Linq上运行速度提高30倍(与Management Studio一样快)?

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

这可能对你有所帮助 -

DECLARE 
      @p0 INT
    , @p1 INT
    , @p2 DATETIME
    , @p3 DATETIME

SELECT 
      @p0 = 4
    , @p1 = 666685
    , @p2 = '20130201 12:00:00'
    , @p3 = '20130523 12:00:00'

SELECT * 
FROM dbo.TV_TRACKER_ORDER t0
WHERE t0.[STATE] = @p0
    AND t0.HAULIER = @p1
    AND @p2 <= t0.SCHEDULED_DELIVERY_DATE 
    AND t0.SCHEDULED_DELIVERY_DATE <= @p3
ORDER BY t0.G_NUMBER