sql - The multi-part identifier could not be bound error on a function with cursor inside -
i have function takes student id input , returns average grade of student.
i'm not sure why i'm getting bound error. because of fetch next command?
the courseenrollment table has 2 columns, studentid, courseid , finalgrade
create function dbo.personalaverage ( @studentid varchar(20) ) returns decimal begin declare @averagegrade decimal(5,2) declare @totalmarks int declare @numberofcourses int set @averagegrade=0 set @totalmarks=0 set @numberofcourses=0 declare calculateaverage cursor select finalgrade courseenrollment @studentid=dbo.courseenrollment.studentid open calculateaverage while @@fetch_status=0 begin set @numberofcourses = @numberofcourses + 1 set @totalmarks = @totalmarks + dbo.courseenrollment.finalgrade fetch next calculateaverage @totalmarks end if @numberofcourses>0 begin set @averagegrade = @totalmarks/@numberofcourses end close calculateaverage deallocate calculateaverage return @averagegrade end;
corrected version:
create function dbo.personalaverage ( @studentid varchar(20) ) returns decimal(5,2) begin declare @finalgrade int declare @averagegrade decimal(5,2) declare @totalmarks decimal(5,2) declare @numberofcourses int set @averagegrade=0 set @totalmarks=0 set @numberofcourses=0 set @finalgrade=0 declare calculateaverage cursor select dbo.courseenrollment.finalgrade dbo.courseenrollment @studentid=dbo.courseenrollment.studentid , dbo.courseenrollment.finalgrade not null open calculateaverage fetch next calculateaverage @finalgrade while @@fetch_status = 0 begin set @numberofcourses = @numberofcourses + 1 set @totalmarks = @totalmarks + @finalgrade fetch next calculateaverage @finalgrade end if @numberofcourses>0 begin set @averagegrade = @totalmarks/@numberofcourses end close calculateaverage deallocate calculateaverage return @averagegrade end;
i think need initial
fetch next calculateaverage @totalmarks
between
open calculateaverage
and
while @@fetch_status=0
what gordon said. use of cursor here misguided, can sort of calc using sql aggregation. avg...group by.
i suspect error in set @totalmarks = @totalmarks + dbo.courseenrollment.finalgrade there no reference dbo.courseenrollment available in line.
note: having trouble making formatting stick.
with declarations:
declare @finalgrade decimal(5,2)
then open calculateaverage; fetch next calculateaverage @finalgrade
while @@fetch_status=0
begin set @numberofcourses = @numberofcourses + 1 set @totalmarks = @totalmarks + @finalgrade -- @finalgrade fetch next calculateaverage @finalgrade end
Comments
Post a Comment