views:

129

answers:

3

Do linq generated queries get cached effectively by SQL Server 2008?

or is it better to use stored procedures with linq or what about a view and then using compiled linq queries... opinions?

cheers

emphasis here is on "effectively", and or is it better....

ie. views are cached well by sql server, and then using linq on the view....

+1  A: 

L2S simply passes queries on to SQL Server 2008. So they will get cached, or not cached, like any other query submitted by any other process. The fact that a Linq query is compiled has no impact on how SQL Server processes the query.

Randy Minder
i realize that the compiled query has no impact on the sql server but on the complete process, ie. the expression tree parsing etc.So if that is compiled and then using a cached view/stored proc...
alex
@alex - It doesn't make any difference what L2S does to prepare to send the query, whether it's a compiled query, expression tree parsing etc, it has zero impact on how SQL Server processes the query. Many factors go into whether SQL Server will reused a cached query, but L2S has nothing to do with this.
Randy Minder
+1  A: 

Queries that LINQ generates are normal SQL queries like your own hand-crafted SQL queries, and they follow the same rules: if the query text is identical (down to the last comma and whitespace) than a query text before, chances are its query execution plan might have been cached and thus able to be reused.

The point is: the query text has to be absolutely identical - if even a single whitespace is different, SQL Server considers it a new query and thus will go through the full process of parsing, analysing, finding a query plan and executing it.

But basically, yes - queries sent off by LINQ will be cached and reused - if they meet those criteria!

marc_s
i thought ms sql 2008 can decide to use simple parametrization...sql 2008 internals p 533...and also the posibility of forced parametrization
alex
yes, if you have a parametrized query, then you have the identical query text for a number of repeated requests - and then the query plan will most likely be cached and reused
marc_s
+1  A: 

On top of the answers already given according to Damien Guard there's a glitch in the LINQ to SQL and EF LINQ providers that fails to set the variable lengths consistently for queries involving string parameters.

http://damieng.com/blog/2009/12/13/sql-server-query-plan-cache

Apparently it's fixed in .NET 4.0.

In the past I've written stored proc's in place of LINQ queries, mainly for complex reporting-like queries rather than simple CRUD but only following profiling of my application.

sighohwell
eeek thats ugly...didn't know that about linqso what about views...
alex
Views would be treated in exactly the same way as tables.
sighohwell