SQLUSA
SQL Server 2005 Administration
Multi-Dimensional Business Intelligence
SQL Server 2005 Programming
Crash Course in SQL Server 2005

Microsoft SQL Server 2005 Best Practices

How to build a junction table with nested cursors?

 

The following example consists of an outer cursor for book titles and an inner cursor for the author(s):

use pubs


set nocount on
declare @BookTitle varchar(10), @AuthorID varchar(25)
declare @Result table ( Title varchar(100), Author varchar(20))

declare curBookTitle cursor for
select title_id
from titles
order by title_id

open curBookTitle
fetch curBookTitle into @BookTitle
while (@@fetch_status = 0 )
Begin
print 'OUTER LOOP'
declare curTitleAuthor cursor for
select au_id
from titleauthor
where title_id = @BookTitle
open curTitleAuthor
fetch curTitleAuthor into @AuthorID

while (@@fetch_status = 0 )
Begin
print ' INNER LOOP'

insert @Result
select @BookTitle, @AuthorID
fetch curTitleAuthor into @AuthorID
End
close curTitleAuthor
deallocate curTitleAuthor
fetch curBookTitle into @BookTitle
End
close curBookTitle
deallocate curBookTitle


select * from @Result
go


 

The World Leader in SQL Server Training
 
SQLUSA.com Home Page