nhibernate multicriteria CTE subquery
I currently have a MultiCriteria query, which filters the results based on the ids being within a sub query
Subqueries.PropertyIn("Id", detachedCriteria)
The sub query is the same for all queries used in the multicriteria query.
It seems a bit ugly looking at the sql that the sub query is repeated, in my current case 15 times.
开发者_如何学JAVAThe reason for the separate queries is each one has different joins, and don't want one massive Cartesian join.
If I was writing the sql by hand I would pull out the repeated sub query into a common table expression
WITH XYZ AS
{
....
}
and then the sub query would be where id in XYZ in the 15 queries.
This is a bit sql server specific, an alternative would be a temporary table, or other database specific feature.
Any ideas of how to improve the query, or am I stuck with the sub queries being duplicated?
Well, if you're returning multiple result sets, using WITH
won't help you anyways because it can only apply to a single SELECT
statement.
In any event, to make the data layer code database-agnostic, I would probably shove the actual query logic into a stored procedure. This means you can go to town using engine-specific features because it's all hidden behind the public interface. Yes, you'll have to reimplement the query for each database engine you support (which is normally very few), but you get full control over what gets run on each engine, and your data access code will be a heck of a lot cleaner.
精彩评论