I'm writing a long-winded querying system that makes use of CTEs to build valid SQL. There's a possibility it could create up to a thousand expressions within even a simple system, and I'm worried I may hit a limit in the future and have to rework the system.
I've searched high and low but I can't find the answer. What I want to know is:
What is the maximum number of expressions allowed in a CTE?
NOTE: I am not using recursion.
My best guess is I'm limited by the number of characters allowed per batch (see Maximum size for a SQL Server Query? IN clause? Is there a Better Approach)
EDIT
Test code below. My development machine oddly stopped at 600 exactly.
DECLARE @i int = 1, @q varchar(max);
SET @q = 'WITH[0]AS(SELECT 1 AS c)'
WHILE @i < 600
BEGIN
SET @q = @q + ',[' + CONVERT(varchar, @i) + ']AS(SELECT * FROM[' + CONVERT(varchar, @i-1) + '])';
SET @i = @i + 1;
END;
SET @q = @q + 'SELECT * FROM[' + CONVERT(varchar, @i-1) + ']';
EXEC (@q);
I'll see about getting this tested on production servers, but that will take a while.