Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Loop through a recordset in a stored procedure

Status
Not open for further replies.

GJP55

Technical User
Feb 2, 2003
220
GB
Is there a simple method to loop through a table in SQL ?
I am trying to write a stored procedure that takes some field values from a table row and uses them as passed variables in a stored procedure.

I can step through a record set easily using a front end application like access but I want to do this completely in SQL for the time being.

Example:

TestTable contains 3 fields:

ValidationFlag
Criteria
Portfolio

There might be 5 records in there with the same portfolio value and so I would want to call the stored procedure 5 times, each time passing back the different ValidationFLag and Criteria field for that row.

Is this a simple thing to do in SQL ?

Thanks
 
The simple way is not to step through rows in a table with SQL server!!

What you need to do is find a statement that causes all your rows to be updated once. This runs faster and has less impact on concurrent activities and logging.

HOWEVER...
you could use a CURSOR (Which i hate - they are almost as evil as null values) or...

The bits in blue are the keys.. (Still less overhead than a cursor and it does give you row by row processing)
Code:
declare @name varchar(200)
set @name = ''
while not @name is null
begin
  select @name = [blue]min(Name)[/blue] from sysobjects where type = 'u' and [blue]name > @name[/blue]
-- if you pass the end of the records the value will be null
  if not @name is null
    begin
      print @name
    end
 end
 
Thats just what I was looking for.

Thanks very much.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top