Quick Posts C# Nuggets March 12th 2010
Jan 26

I found this nice article on using cursors to loop through a result set in a stored proc and take actions based on the value in the looped row:

This method will loop through all rows of a table regardless of what type the primary key is.

use YourDatabaseNameHere
go

declare @Field1 int
declare
@Field2 int
declare
@Field3 int

declare MyCursor cursor fast_forward for
select
Field1, Field2, Field3 from YourTableNameHere

open MyCursor
fetch next from MyCursor
into @Field1, @Field2, @Field3

while @@fetch_status = 0
begin
— Perform Operations
declare myTest int
myTest = @Field1 + @Field2 + @Field3

– Advance the Cursor
fetch next from MyCursor
into @Field1, @Field2, @Field3
end

close MyCursor
deallocate MyCursor
go

This was on the following site: http://www.bunkerhollow.com/blogs/matt/archive/2009/03/10/ms-sql-loop-through-table-scripts.aspx

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google

2 Responses to “Looping through select statement results in MSSQL”

  1. Kylie Batt Says:

    Согласен, это забавная фраза…

    This method will loop through all rows of a table regardless of what type the primary key is…..

  2. ВАн4ezzZ Says:

    УРА.!…

    Всех с 1 мая!…

Leave a Reply

Spam Protection by WP-SpamFree