我不太确定我输入的内容是错误的。这是我从SQL代码收到的错误:
Msg 102,Level 15,State 1,Procedure GradeAverage,Line 22
'myCursor'附近的语法不正确。
功能:
CREATE FUNCTION GradeAverage
(@StudentID as varchar(20))
RETURNS int
AS
BEGIN
DECLARE @Final int
DECLARE @Grade int
DECLARE @Total int= 0
DECLARE @Count int = 0
DECLARE myCursor CURSOR FOR
SELECT FinalGrade
FROM CourseEnrollment
WHERE StudentId = @StudentID AND FinalGrade IS NOT NULL
OPEN myCursor;
FETCH NEXT FROM myCursor INTO @Grade
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Total = @Grade + @Total;
SET @Count = @Count +1;
FETCH NEXT FROM myCursor INTO @Grade
END
SET @Final = (@Total/@Count);
CLOSE myCursor
DEALLOCATE myCursor
RETURNS @Final
答案 0 :(得分:1)
第一个问题是RETURNS
声明函数的返回类型,如RETURNS int
中所示,但要实际指定返回值,您需要使用RETURN
(否S
):
第二个问题是,函数定义中的每个BEGIN
都必须与END
匹配,包括围绕整个函数体的BEGIN
/ END
。
最后,为了便于阅读,我建议您采用一些更标准的格式约定。它应该是这样的:
CREATE FUNCTION GradeAverage (@StudentID as varchar(20)) RETURNS int
AS
BEGIN
DECLARE @Final int;
DECLARE @Grade int;
DECLARE @Total int= 0;
DECLARE @Count int = 0;
DECLARE myCursor CURSOR FOR
SELECT FinalGrade
FROM CourseEnrollment
WHERE StudentId = @StudentID AND FinalGrade IS NOT NULL;
OPEN myCursor;
FETCH NEXT FROM myCursor INTO @Grade;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Total = @Grade + @Total;
SET @Count = @Count +1;
FETCH NEXT FROM myCursor INTO @Grade;
END
SET @Final = (@Total/@Count);
CLOSE myCursor;
DEALLOCATE myCursor;
RETURN @Final;
END