-- Illustrate doing a join vs ISAM like looping . A huge performance diff.-- Look at the value of @stmt_counter to see how many commands SQL Server-- must execute in the cursor case/
use pubs
SET NOCOUNT ON
go
--- The select statement is lightning fast !SELECT A.au_id, au_lname, title
FROM authors A
JOIN titleauthor TA ON (A.au_id=TA.au_id)
JOIN titles T ON (T.title_id=TA.title_id)
ORDERBY A.au_id, title
go
-- Now a cursor solution - order of magnitude slower.
PRINT ''
PRINT ''
GO
declare@au_idchar(11),@au_lnamevarchar(40),@title_idchar(6),@au_id2char(11),@title_id2char(6),@titlevarchar(80),@stmt_counterintDECLARE au_cursor CURSORFORSELECT au_id,au_lname FROM authors ORDERby au_id
DECLARE au_titles CURSORFORSELECT au_id,title_id FROM titleauthor ORDERBY au_id
DECLARE titles_cursor CURSORFORSELECT title_id,title FROM titles ORDERBY title
OPEN au_cursor
select@stmt_counter=5-- delcare variables, three cursor declares and an open so far).FETCH NEXT FROM au_cursor INTO@au_id, @au_lnameselect@stmt_counter=@stmt_counter+1
WHILE (@@FETCH_STATUS=0 )
BEGINOPEN au_titles
FETCH NEXT FROM au_titles INTO@au_id2,@title_idselect@stmt_counter=@stmt_counter+2-- An Open & Fetch every time through
WHILE (@@fetch_status=0)
BEGIN-- If this is for the current author, then get titles too
IF (@au_id=@au_id2)
BEGINOPEN titles_cursor
FETCH NEXT FROM titles_cursor INTO@title_id2,@titleselect@stmt_counter=@stmt_counter+2-- An Open & Fetch every time through
WHILE (@@fetch_status=0)
BEGIN-- If right title_id, then display the values
IF (@title_id=@title_id2)
SELECT@au_id,@au_lname,@titleFETCH NEXT FROM titles_cursor INTO@title_id2,@titleselect@stmt_counter=@stmt_counter+2-- At min, a Fetch every timeENDCLOSE titles_cursor
ENDFETCH NEXT FROM au_titles INTO@au_id2,@title_idENDCLOSE au_titles
FETCH NEXT FROM au_cursor INTO@au_id,@au_lnameselect@stmt_counter=@stmt_counter+2-- An Open & Fetch every time throughENDCLOSE au_cursor
DEALLOCATE titles_cursor
DEALLOCATE au_titles
DEALLOCATE au_cursor
select@stmt_counter=@stmt_counter+4-- Close and Deallocateselect@stmt_counter