This is not a direct answer to your question, but maybe you can think about it:
SQL Server seems to limit the semantics (not necessarily syntax) of SQL, where it makes sense to do so. For example, you cannot have a subquery with an ORDER BY unless you also specify a TOP n clause. This makes sense, since ordered subqueries are pointless if they have no restrictions. Other DBMSs allow such meaninglessness.
In your case (this is just a hunch), having CTEs in subqueries has limited meaning, because you can rewrite the entire request so that CTEs are declared at the highest level. The only difference you will have is the scope and possibly the readability of each declaration.
CTE, on the other hand, allows recursive queries, which can be very difficult to apply when CTEs are declared in subqueries ...
Since you need to implement SQL agnostic SQL, I recommend that you not use CTE yet. If CTEs are simple, you can always rewrite them as simple representations ...
Lukas Eder
source share