I have this SQL that I’d like to convert to a BAQ. Do you know How I would set this up? I need a CTE to generate a specified row of numbers. Ultimately using this BAQ to feed a BAQ report to generate some labels.
declare @begNumber as int = 1
declare @endNumber as int = 50
--print 1 to 50 numbers
; with CTE as
(select @begNumber Number
union all
select Number +1 from CTE where Number < @endNumber
)
select * from CTE
This works if your iteration is less than 100. On SaaS, that’s set in stone. If you’re self hosted, you could change the value of MAXRECURSION, but keep in mind it’s like that because of reasons, and you have access to a better solution anyway.
Recursion limitation isn’t the end of the world. It’s easy to CTE your way to arbitrary sequences!
with foo as(
select
null as whatever
union all
select
null as whatever
), tally as)
select
row_number() over(order by foo.whatever) as increment
from foo --< returns two rows
join foo as a on 1=1 --< cross joins two rows: 2 * 2 = 4 rows
join foo as b on 1=1 --< 8 rows
join foo as c on 1=1 --< 16 rows
join foo as d on 1=1 --< 32 rows
-- see where this is going?
)
That’s how you get to arbitrary iteration in SQL, without recursion. It’s as performant as you’re going to get on SaaS. If you’re self hosted, this is how you can populate a tally table (literally, create table tally(increment int primary key);) that SQL Server will cache in memory for best possible performance.
If you are doing recursion that is more than 100 levels deep you are probably using the wrong application or doing something incorrectly.
Recursion is very expensive (in all/most languages) as it requires full stack chain replication. Every iteration adds a new reference frame to the call stack and would eventually overflow you. It is a powerful tool, but Spiderman Rules apply.