I'll start by confessing that this if my first cursor. Someone on this forum helped me get started but I'm still stuck.

Summary: I'm trying to loop through a set of hospitals and for each identify their top 5 claim denial reasons by dollars denied. I'd also like to tag each reason for each hospital, 'Top1' , 'Top2' through 'Top5' in DESC order for dollars denied for each hospital.

Here's the errors I'm getting.

Server: Msg 170, Level 15, State 1, Line 3
Line 3: Incorrect syntax near '('.
Server: Msg 137, Level 15, State 1, Line 15
Must declare the variable '@outputtable'.
Server: Msg 137, Level 15, State 1, Line 23
Must declare the variable '@PeriodID'.
Server: Msg 137, Level 15, State 1, Line 37
Must declare the variable '@outputtable'.

Here's my query (note: provider = hospital)

declare @provider varchar(16)
Declare @status int
declare @outputtable (PeriodID int, ProviderName varchar(50), AltProviderID_1 char(15),
EOPCode smallint, ISDenial smallint, DeniedAmount money)

declare C cursor LOCAL for select providerid from Prov_Rep_list

-Prov_Rep_List a table with the list of providers

open C fetch next from C into @provider
set @status=@@fetch_status

while @status = 0

begin
insert into @outputtable
SELECT TOP 5 l.PeriodID, p.ProviderName, p.AltProviderID_1,
e.EOPCode, l.ISDenial,
SUM(l.DeniedAmount) AS DeniedAmount
FROM dvOperationalLine l
INNER JOIN dimProvider p
ON l.ProviderID = p.ProviderID
INNER JOIN dimEOP e
ON e.EOPCodeID = l.EOPCodeID
WHERE l.PeriodID = @PeriodID
AND ISDenial = 1
AND (p.AltProviderID_1 = @provider
)
GROUP BY l.PeriodID, IsDenial, p.ProviderName,
p.AltProviderID_1, e.EOPCode
ORDER BY DeniedAmount DESC

fetch next from C into @provider
set @status=@@fetch_status
end

close C
deallocate C
select * from @outputtable

I appreciate your help and patience.

Ray