SQL Server &c#存储过程&除以零例外
本文关键字:零例 Server 存储过程 SQL | 更新日期: 2023-09-27 17:49:58
首先是我的c#代码,然后是存储过程。
public DataTable GetCourseHighPass(String tmpCourse)
{
command.Connection = OpenConnection();
try
{
command.CommandText = "exec GetCourseCompletions @tmpCourse = '" + tmpCourse + "'";
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
dataAdapter.Fill(dataTable);
return dataTable;
}
catch (Exception)
{
throw new Exception("There are no VG's for this course.");
}
finally
{
command.Connection.Close();
}
}
这是我的存储过程。
create procedure GetCourseCompletions
@tmpCourse nvarchar(30)
as
select (count(pnr) * 100 / (select count(pnr)
from HasStudied
where courseCode = @tmpCourse
and count(pnr) =)) as VGPrecentage
from HasStudied
where grade >= 5
and courseCode = @tmpCourse
go
问题是,如果没有学生通过高分,我将得到一个除零异常。寻找关于如何捕获这个异常的建议,这样程序就不会崩溃,或者甚至更好地重写存储过程,这样它就不会在第一时间得到异常。
谢谢你的帮助!
按Eric说的做:
DECLARE @count int
Set @count = (select count(pnr) from HasStudied where courseCode = @tmpCourse and count(pnr) =...)
IF @count = 0
BEGIN
SELECT 0 as VGPrecentage
END
ELSE
BEGIN
select (count(pnr)*100 / @count) as VGPrecentage from HasStudied where grade >= 5 and courseCode = @tmpCourse
END
我建议您使用这种查询,而不是您的查询,将处理NULL值和零值:
SELECT
CASE WHEN part * total <> 0 THEN part * 100 / total ELSE 0 END
FROM (
SELECT SUM(CASE WHEN grade > 5 THEN 1.00 ELSE 0.00 END) As part, SUM(1.00) as total
FROM HasStudied
WHERE courseCode = @tmpCourse) t