Ms sql 2008 - MAXRECURSION
To stop a statement after a defined number of loops is called maxrecursion.
Below example is showing to stop infinite loop.when you CTE is going to 4th recursion it will throw an error and stop executing.If you put MAXRECURSION value too low it may be possible before your desire result and will throw an error.
WITH AamirHasan_CTE(id) AS
(
SELECT 1
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 4
UNION ALL
SELECT 5
UNION ALL
SELECT 6
)
SELECT *
FROM AamirHasan_CTE
OPTION (MAXRECURSION 4);