I've had a project dumped in my lap, and I'm pretty far outside of my element. There is a table with roughly 10,000,000 rows that is being queried. There is one query in particular that is taking too long to run, and is timing out. The query generated by Linq is
-- Region Parameters
DECLARE @p0 Int = 335
DECLARE @p1 DateTime = DATEADD(day,-7,GETDATE())
-- EndRegion
SELECT *
FROM [Events] AS [t0],
[Devices] AS [t1],
[EventTypes] AS [t2],
[DeviceTypes] AS [t3]
WHERE ([t1].[DeviceID] = [t0].[DeviceID])
AND ([t2].[EventTypeID] = [t0].[EventTypeID])
AND ([t3].[DeviceTypeID] = [t1].[DeviceTypeID])
AND ([t1].[RoomID] = @p0)
AND ([t0].[EventTime] >= @p1)
If I change the last line to be [t0].[EventTime] >= DATEADD(day,-7,GETDATE())
instead of using the variable @p1
, the query goes from taking 45 seconds to run, to taking 3 seconds to run.
My two questions are 1) Why does this simple change increase performance so drastically and 2) is there a way to force Linq to not use the variable and inline the datetime object?
The Linq code is C# .NET 3.5 and the server is MSSQL 2005
Edit: I added the SELECT * for brevity, the actual query does not do that.