Wednesday, March 21, 2012

LOOP in SQL

Hello,
Quick Question...
I have a need to use a FOR NEXT loop in my Query. Is that allowed? I
haven't been able to find the FOR keyword in the Transact-SQL Reference.
What is the syntax for a Conditional Loop. DO, WHILE, '
Thanks,
DBALWHILE (<condition> )
BEGIN
<code>
END
"DBAL" wrote:

> Hello,
> Quick Question...
> I have a need to use a FOR NEXT loop in my Query. Is that allowed? I
> haven't been able to find the FOR keyword in the Transact-SQL Reference.
> What is the syntax for a Conditional Loop. DO, WHILE, '
> Thanks,
> DBAL|||-- ---
Declare @.Index Integer Set @.Index = 1
While @.Index < 1000
Begin
<do Some stuff here>
Set @.Index = @.Index + 1
End
-- ---
"DBAL" wrote:

> Hello,
> Quick Question...
> I have a need to use a FOR NEXT loop in my Query. Is that allowed? I
> haven't been able to find the FOR keyword in the Transact-SQL Reference.
> What is the syntax for a Conditional Loop. DO, WHILE, '
> Thanks,
> DBAL|||Nice! Thanks alot.
DBAL
"CBretana" wrote:
> -- ---
> Declare @.Index Integer Set @.Index = 1
> While @.Index < 1000
> Begin
> <do Some stuff here>
> Set @.Index = @.Index + 1
> End
> -- ---
> "DBAL" wrote:
>|||What do you want to do? SQL is primarily a declarative data manipulation
language. In general it's best to avoid loops for data manipulation
operations.
David Portas
SQL Server MVP
--|||I've found loops handy for very large update operations on underpowered
computers during development :) Instead of trying to Update 500,000,000
rows of a table at once, I can update a couple million at a time. Plus, if
the query crashes (as they seem to do on desktop computers with only 512MB
and a hard drive over 85% full), at least I can restart at the point it
stopped at without restarting from scratch.
...Obviously I wouldn't do anything like this in production code (the
production machines have plenty of resources) :)
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:u9idnaYzkeTRKObfRVn-jA@.giganews.com...
> What do you want to do? SQL is primarily a declarative data manipulation
> language. In general it's best to avoid loops for data manipulation
> operations.
> --
> David Portas
> SQL Server MVP
> --
>|||That's a good point. The exceptions prove the rule I guess.
David Portas
SQL Server MVP
--|||It is true! But your question was perfectly valid. We need to question
usage like this because 99% of the time, if someone is trying to figure out
how to do a loop, they are not using it to cover the exceptions :)
Hopefully DBAL will see your post as well as Michaels, and all of the
others.
----
Louis Davidson - http://spaces.msn.com/members/drsql/
SQL Server MVP
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:xpGdncaIu5bk4eHfRVn-sA@.giganews.com...
> That's a good point. The exceptions prove the rule I guess.
> --
> David Portas
> SQL Server MVP
> --
>sql

No comments:

Post a Comment