SQLUSA

Microsoft SQL Server 2008 Best Practices

How to apply nested cursors and XML path?

 

Execute the following script in Query Editor to generate a book title - author junction table representing many-to-many relationship. XML Path is used to generate a list of authors for books with multiple authors.

use pubs;

 

set nocount on

 

declare @BookTitle varchar(16), @AuthorID varchar(32)

declare @Result table ( Title varchar(128), Author varchar(32))

 

-- Outer cursor

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'

 

-- Inner nested cursor

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

 

-- Junction table simple listing

select * from @Result

order by Title, Author

 

-- Books with multiple authors listed on one line

-- XML path - text() will generate a comma separated list

select distinct title,

AuthorList=STUFF((select ', '+ Author as [text()] from  @Result r

where r.Title = r1.Title

order by Author

for XML Path ('')), 1, 1, '')

from @Result r1

go

 

 

SQLUSA - The Best SQL Server 2008 Training in the World
 
 
SQLUSA.com Home Page