Loop without Cursors
Every one talks about avoiding cursors. The simplest possible way to do this is what I mentioned below.
Before you look at the example, here is what I am aiming at:
I have a students' grades table. I need a set of rows from this table which meets certain criteria, in this case students' whose grade is C.
After I get the set of rows I want to loop through this set of rows.
Though not a great reason to loop through the table, the basic aim is achieved in the following stored procedure i.e traverse the table with out the need of cursors in a simple way.
Create proc sp_looptable
as
-- temptable is the table which holds the result set.
-- Note that I used PrimaryKey field which is set to autoincrement by 1 for each
-- insert
declare @temptable table(PrimaryKey int IDENTITY (1, 1) NOT NULL,SSN int)
-- rCount is a variable which is the number of rows in the table we need to loop
declare @rCount int
-- value to store SSN in temporary table
declare @tempSSN int
-- Insert values into temporary table. Fk_SSN is the foriegn key
-- in the students' grades table
Insert Into @temptable
Select Fk_SSN From TblStudentGrades where Grade = 'C'
-- rCount holds the value of number of rows inserted
SET @rCount = @@ROWCOUNT
-- loop through the table
While @rCount <> 0
Begin
-- Here, you can retrieve the values from the temporary table
select @tempSSN=SSN From @temptable where PrimaryKey= @rCount
Set @rCount = @rCount -1
End
-----------------------------------------------------------------------
Do visit to see more useful articles being added not found in any book.

0 Comments:
Post a Comment
<< Home