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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Looping recordsets in stored procedures

Status
Not open for further replies.

multiplex77

Programmer
Dec 25, 2001
302
SG
Hi,

I have a complex set of queries I need to invoke in order to get my desired record set, which I'm using a stored procedure for. I need to loop through the recordsets of the first select query, to analyze a second table, but don't know how to look at individual records of that record set.

If I'm using ASP, I would just do...

objRS.Open "SELECT table1_ID, Name1 FROM table1"

While Not objRS.EOF
objRS2.Open "SELECT * FROM table2 " & _
"WHERE ID = " & objRS("table1_ID") & _
" Name = '" & objRS("Name1") & "'"
objRS.MoveNext
Wend

However, using T-SQL, I don't know how to loop through resultsets. Could someone please help me?

Thanks very much, in advance.

...and then
 
Sounds like you need to use a Cursor, e.g.

DECLARE @table1_ID INT
DECLARE @Name1 VARCHAR(50)

DECLARE csSomeCursor CURSOR LOCAL FAST FORWARD FOR
SELECT table1_ID, Name1 FROM table1

OPEN csSomeCursor

FETCH NEXT FROM csSomeCursor INTO @table1_ID, @Name1

WHILE @@FETCH_STATUS = 0
BEGIN
SELECT * FROM table2 WHERE ID = @table1_ID AND Name = @Name1
FETCH NEXT FROM csSomeCursor INTO @table1_ID, @Name1
END

CLOSE csSomeCursor
DEALLOCATE csSomeCursor

Hope that helps

Nathan
 
declare @tbl_id <some datatype>, @tbl_name <some datatype>
declare rset1 cursor
for
SELECT table1_ID, Name1 FROM table1

open rset1
fetch rset1 into @tbl_id , @tbl_name
while @@fetch_status = 0
begin
SELECT * FROM table2
WHERE ID = @tbl_id
and Name = @tbl_name
fetch rset1 into @tbl_id , @tbl_name
end
close rset1
deallocate rset1

RT
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top