Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it so difficult to do a loop in T-SQL

OK, I know it can be done, I do it quite often, but why so difficult to do a loop in T-SQL? I can think of a ton of reasons I'd want to parse thru a query result set and do something that simply can't be done without a loop, yet the code to setup and execute my loop is > 20 lines.

I'm sure others have a similar opinions so why are we still without a simple way to perform a loop?

An aside: we finally got an UPSERT (aka MERGE) in SQL2008 so maybe all hope isn't lost.

like image 270
Kyle West Avatar asked Feb 25 '09 21:02

Kyle West


2 Answers

SQL is a set-based, declarative language; not a procedural or imperative language. T-SQL tries to straddle the two, but it's still built on a fundamentally set-based paradigm.

like image 185
Rex M Avatar answered Nov 25 '22 07:11

Rex M


I can think of a ton of reasons I'd want to parse thru a query result set and do something that simply can't be done without a loop

And for the vast majority of those I can either show you how to do it in a set-based operation instead or explain why it should be done in your client code rather than on the database. Needing to do a loop in sql is exceeding rare.

like image 28
Joel Coehoorn Avatar answered Nov 25 '22 07:11

Joel Coehoorn