I have a query in a view using a recursive cte on a large tree that works well when querying with a hard-coded number, but not with a parameter. Is it possible to get SQL Server to use the plan that I want to optimize for this recursive cte query? Any ideas would be appreciated.
Here is a view with a recursive CTE - it retrieves all the nodes under this object:
CREATE VIEW adams_test_view AS
WITH eq_mi_cte(miId, eqId, miName, miCode) AS
(SELECT ent.id, ent.id, ent.name, ent.code
FROM entity ent
UNION ALL
SELECT e.id, eq_mi_cte.eqid, e.name, e.code
FROM entity e
INNER JOIN eq_mi_cte ON e.pid = eq_mi_cte.miid)
SELECT * FROM eq_mi_cte
A view request with a parameter seems to request the whole view and then filters it, which never ends as the tree is too large - we get the maximum recursion error:
DECLARE @TopLevelEnt int
SET @TopLevelEnt = 187317;
select * from adams_test_view
WHERE eqId = @TopLevelEnt
Here is a plan (my applications for index names):
|
|
|
|
| |
|
|
|
| |
|
, , :
:
SELECT * FROM adams_test_view
WHERE eqId = 187317
:
|
|
|
| |
|
|
|
| |
|
pk sp_updatestats, .
, , , , .
DECLARE @TopLevelEnt int
SET @TopLevelEnt = 187317;
select * from adams_test_view
WHERE eqId = @TopLevelEnt
OPTION (OPTIMIZE FOR (@TopLevelEnt = 187317))
SQL Server 2005 Express SQL Server Management Studio Express 2008 R2
.