I do not know if this will be a question that many pose, but I have always had it in mind almost always.
Normally when I need to deliver a corrective script to a client, used to only run once, I use a CURSOR
, perhaps because it is more readable for people who do not know much about TSQL and because it is, in a way, simpler to maintain (recursion can often "complicate").
But in development I try, whenever possible, to use CTE
because it is " what to use" , according to those who understand it.
So I question: CTE or CURSOR ?
I know that CTE is supposed to offer more performance compared to CURSOR, but is it enough to use it to the detriment of the other option?
The issue of recursion, as I mentioned above, can often complicate a simple process, and may even make it difficult to maintain a multi-level script in a more complex scenario.
In CTE
we are not able to see exactly what is executed in the middle, whereas with CURSOR
we can put a PRINT
or SELECT
with important or useful information in a debug process or validation of results.
In short, does using a CURSOR
with a temporary (eg), or even a WHILE
, cycle is so worse than using a CTE?
Of course it should depend on the scenario, but where should we use one and the other?