Question

I have a rather complicated SQL view in my SQL Azure database. When I get into SQL Management Portal and run

SELECT TOP(1) * FROM MyComplicatedView WHERE Id = 'SomeSpecificValue'

the query finishes in about 3 seconds. Now I have some code that reads that view via Linq-to-Sql. I have a Table-attributed class mapped onto that view:

[Table]    
class MyComplicatedView {
   [Column]
   public Guid Id {get;set;}

   // several more columns here
}

and my code uses DataContext:

var context = new DataContext(connStr);
context.Log = Console.Out;
var table = context.GetTable<MyComplicatedView>();
var first = table.FirstOrDefault(item => item.Id == "SomeSpecificValue");

and this time it takes about 30 seconds and then times out. The console output (taken from here) shows that the query contains a SELECT TOP(1) - almost the same as the query I run via the portal:

SELECT TOP (1) [t0].[Id], [t0].[OtherColumn1], [t0].[OtherColumn2], --etc
FROM [MyComplicatedView] AS [t0]
WHERE [t0].[Id] = @p0
-- @p0: Input UniqueIdentifier (Size = 0; Prec = 0; Scale = 0) [SomeSpecificValue]

and when I run the previous query via the portal with the same parameter value I get the same nice timing (around 3 seconds):

SELECT TOP (1) [t0].[Id], [t0].[OtherColumn1], [t0].[OtherColumn2], --etc
FROM [MyComplicatedView] AS [t0]
WHERE [t0].[Id] = 'SomeSpecificValue'

and finally I run the following code in the portal:

DECLARE @p0 uniqueidentifier;
SET @p0 = 'SomeSpecificValue';
SELECT TOP (1) [t0].[Id], [t0].[OtherColumn1], [t0].[OtherColumn2], --etc
FROM [MyComplicatedView] AS [t0]
WHERE [t0].[Id] = @p0

and the timing is now much worse - something close to 10 seconds and still much better that that of the query that times out.

Why the timing difference? How do I get good timing all the time?

Was it helpful?

Solution

The answer I think is to check the execution plans of both queries. You may be a victim of SQL Server parameter sniffing as explained here Why does a parameterized query produces vastly slower query plan vs non-parameterized query

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top