views:

33

answers:

1

Is it possible to use CTE in a WHERE clause e.g.

SELECT * 
  FROM Table1 
 WHERE Table1.PK IN (
   WITH Cte AS (
    -- root selection (dynamic, generated in code)
    SELECT Bla FROM Table2
    -- recursive part
    UNION ALL
    SELECT …..)
  SELECT Bla FROM Cte)

The reason I’m asking is that I need to use a recursive query and the only way of doing it at the moment without updating our framework is to place it in the where clause.

+3  A: 

No, WITH clauses need to be defined before the main SELECT. Like this:

WITH recursive_cte AS (
   -- root selection (dynamic, generated in code)
   SELECT Bla FROM Table2
   -- recursive part
   UNION ALL
   SELECT …..)
SELECT t.*
  FROM TABLE1 t
  JOIN recursive_cte rc ON rc.key = t.pk

I also tweaked the query to use a JOIN instead, but you'll have to watch for duplicates.

OMG Ponies