我有一个非常简单的 LINQ to Entity Code 来查询 SQL Server 数据库中的数据。我有两个表“MES_WO_Master”“MES_WO_Tracking”,表“MES_WO_Master”在列“WoNo”和“MaterialNo”上有索引,表“MES_WO_Tracking”在“EndDate”列上有索引。LINQ to Entity 如下:
from w in MES_WO_Master
join r in MES_WO_Tracking
on w.WoNo equals r.WoNo
where r.EndDate >= DateTime.Parse("2013-01-02") && r.EndDate <= DateTime.Parse("2013-01-03") && r.QtyScrap > 0 && w.MaterialNo.EndsWith("-W")
select new
{
WoNo = w.WoNo,
MaterialNo = w.MaterialNo,
QtyComplete = r.QtyComplete.Value,
QtyScrap = r.QtyScrap.Value,
ScrapCode = r.ScrapCode,
EndDate = r.EndDate.Value
}
而这个 LINQ To Entity 需要执行超过 30 秒才能获取数据。我使用 LINQPad 来获取此 LINQ 的实际 SQL 语句。声明如下:
-- Region Parameters
DECLARE @p0 VARCHAR(20)
SET @p0 = '2013-01-02'
DECLARE @p1 VARCHAR(20)
SET @p1 = '2013-01-03'
DECLARE @p2 BIGINT
SET @p2 = 0
DECLARE @p3 VARCHAR(3)
SET @p3 = '%-W'
-- EndRegion
SELECT [t0].[WoNo] ,
[t0].[MaterialNo] ,
[t1].[QtyComplete] AS [QtyComplete] ,
[t1].[QtyScrap] AS [QtyScrap] ,
[t1].[ScrapCode] ,
[t1].[EndDate] AS [EndDate]
FROM [MES_WO_Master] AS [t0]
INNER JOIN [MES_WO_Tracking] AS [t1] ON [t0].[WoNo] = [t1].[WoNo]
WHERE ( [t1].[EndDate] >= @p0 )
AND ( [t1].[EndDate] <= @p1 )
AND ( [t1].[QtyScrap] > @p2 )
AND ( [t0].[MaterialNo] LIKE @p3 )
但是,如果我将@p3 替换为“%-W”并在 SQL Server 分析窗口中执行如下语句,则只需要不超过 1 秒。
-- Region Parameters
DECLARE @p0 VARCHAR(20)
SET @p0 = '2013-01-02'
DECLARE @p1 VARCHAR(20)
SET @p1 = '2013-01-03'
DECLARE @p2 BIGINT
SET @p2 = 0
DECLARE @p3 VARCHAR(3)
SET @p3 = '%-W'
-- EndRegion
SELECT [t0].[WoNo] ,
[t0].[MaterialNo] ,
[t1].[QtyComplete] AS [QtyComplete] ,
[t1].[QtyScrap] AS [QtyScrap] ,
[t1].[ScrapCode] ,
[t1].[EndDate] AS [EndDate]
FROM [MES_WO_Master] AS [t0]
INNER JOIN [MES_WO_Tracking] AS [t1] ON [t0].[WoNo] = [t1].[WoNo]
WHERE ( [t1].[EndDate] >= @p0 )
AND ( [t1].[EndDate] <= @p1 )
AND ( [t1].[QtyScrap] > @p2 )
AND ( [t0].[MaterialNo] LIKE ***'%-W'***)
我知道'%-W'不会使用索引,但是为什么这两个语句会有这么大的差距呢?有人可以给我一些提示吗?非常感谢。
杰克