There is no final answer, as it really depends on the situation.
In general, I find it best to keep the logic in sproc as simple and set-based as possible. For example, this is too complicated with several IF statements nested, it can complicate it for the query optimizer, which means that it cannot create a good execution plan suitable for all paths via sproc. For example, the first time sproc is started, it takes path A through logic, and the execution plan reflects this. The next time it starts with different parameters, it takes path B, but re-executes the original execution plan, which is not optimal for this second path. One solution to this is to break down the load into separate stored procedures for calling depending on the path used - this allows you to optimize the routine and execution plan, cached independently.
Loops may be the only viable option, but overall I would try not to use them - always try to do something based on a set, if possible.
source share