• The reason why it is slow is probably the excessive looping.

    SQL Server is optimized to do set-based queries, i.e. all rows at the same time instead of a row at a time.

    If you could explain a bit more what you are trying to do with the code (and maybe provide some sample data), the code can be rewritten.

    Need an answer? No, you need a question
    My blog at https://sqlkover.com.
    MCSE Business Intelligence - Microsoft Data Platform MVP