In SQL Server, the CTE should be at the top of the query. If you build queries dynamically, you can save the CTE list in addition to the query. Before sending a query to the SQL server, you can prefix the query using the CTE list:
; with Cte1 as (...definition 1...), Cte2 as (...definition 2...), Cte3 as (...definition 3...), ... ...constructed query...
It is assumed that you are creating SQL outside of SQL Server.
You may also consider creating views. Views can contain CTEs and can be used as a subquery or view. Views are a good choice if you rarely generate SQL, say, only during installation or as part of a deployment.
source share