I have some dynamic sql that generates the below CTE. The dynamic SQL generates different order by statements depending on the parameter in the SP. Here you can see it was Name
, ORDER BY t.Name ASC
. I believe this creates a new plan for each sort order that is different. Is there a way to only create one plan for this query regardless of the order by?
WITH PagedResults AS
(
SELECT ROW_NUMBER() OVER (ORDER BY t.Name ASC, t.Id ASC) AS [Row],
ROW_NUMBER() OVER (ORDER BY t.Name DESC, t.Id DESC) AS [RowReverse],
t.Id,
FROM
DivisionTeam dt INNER JOIN
Team t ON t.Id = dt.Id
WHERE
t.SportId = @SportId
)