--Now scalable, set based and added a fizzbuzz!
DECLARE @threshold int = 100
;WITH numbers ( seqnum )
AS ( SELECT 1 AS seqnum
SELECT seqnum + 1 AS seqnum
WHERE seqnum < @threshold
Recursive CTEs are questionably set-based (will leave it to you to figure out why) and slower than many other methods of row generation.
I agree with Gail. Recursive CTEs that "count" or process individual rows are a form of "Hidden RBAR" that can be much worse than a well written While Loop. Of course, for the production of regular numeric sequences, both should be avoided. Please see the following article for more information and performance comparisions of 3 other methods that absolutely blow Recursive CTE number generators out of the water even for relatively small numbers of rows.
As Gail also suggested, Recursive CTEs do have some good uses and shouldn't be avoided "just because". As with all else in SQL Server, "It Depends".
is pronounced "ree-bar
" and is a "Modenism
" for R
First step towards the paradigm shift of writing Set Based code:
________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.
"Change is inevitable... change for the better is not".
"Dear Lord... I'm a DBA so please give me patience because, if you give me strength, I'm going to need bail money too!"
How to post code problems
How to Post Performance Problems
Create a Tally Function (fnTally)