0

I am not satisfied with answers on Caching SQL queries.

I am not interested in 3rd party solutions because this should be a simple problem to solve by myself.

I am looking for an alternative solution to Caching of Linq queries which works with any SQL query, not just Linq. Ideal solution would be to have stored procedure like execsql @Sql,@HashCode, which would query table of serialized results by HashCode and return result if exists, otherwise run query, save serialized result in table of results and return it. Of course returned results must have the same structure as if they were not stored.

Let's not worry about cache expiration/garbage cleaning or other possible performance issues in this context.

In order to do that I need to be able to detect hash code of SQL query (I suppose GetHashCode on SQL query string will do), serialize and deserialize query result.

Considering that query results may have different structure, I suppose that utilization of FOR XML AUTO would be a good candidate for serialization. But how to deserialize it in generic way so that code does not depend on result structure ?

The solution can use Sql 2008 features if needed.

Community
  • 1
  • 1
alpav
  • 2,972
  • 3
  • 37
  • 47
  • `Caching ... should be a sinple problem to solve...`: I wish that was true. Is not. Is one of the most difficult problems to solve. – Remus Rusanu Dec 07 '11 at 18:22

1 Answers1

1

you could this like that (a stored proc, that'll wait your table function and your parameters concatenated :

CacheService(tableFunctionName,parametersConcat)

IF(there_is_no_cache_table)
BEGIN
   execsql "SELECT * , "+parametersConcat+" as parametersConcat INTO cache_tableFunctionName "++" FROM dbo."+tableFunctionName+"("+parametersConcat+")"
END
ELSE IF(there_is_no_cache_entry_for_this_function_and_parameters)
BEGIN
   execsql "INSERT INTO cache_"+tableFunctionName+" SELECT * , "+parametersConcat+" FROM dbo."+tableFunctionName+"("+parametersConcat+")"
END
ELSE  
BEGIN
   execsql "SELECT *  FROM cache_"+tableFunctionName+" WHERE parametersConcat ='"+parametersConcat+"'"
END

EDIT : be careful about SQL Injection and everything this is just a starter

EDIT 2 : you might have to add the cache entry creation date so you can delete them

remi bourgarel
  • 9,231
  • 4
  • 40
  • 73
  • In this case ROW_NUMBER() without OVER http://stackoverflow.com/questions/4810627/sql-server-2005-row-number-without-over is useful to serialize sorting. – alpav Dec 07 '11 at 17:50
  • I was wrong about ROW_NUMBER() OVER (ORDER BY (SELECT 1)), it does not preserve sorting, it just adds unique column. I have to extract and inject ORDER BY into OVER. – alpav Dec 07 '11 at 21:50
  • @alpav can you post your implementation so other people might like it ? – remi bourgarel Dec 08 '11 at 16:59