[英]SQL Server & C# Stored Procedure & Divide by Zero Exception
So first here is my C# code and then comes the stored procedure. 因此,这里首先是我的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();
}
}
And here is my stored procedure. 这是我的存储过程。
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
The problem is that if there are no students with a high pass I will get a divide by zero exception. 问题是,如果没有高通的学生,我将被零除。 Looking for suggestions on how to catch this exception so the program does not crash or even better to re-write the stored procedure so it does not get an exception in the first place.
寻找有关如何捕获此异常的建议,以使程序不会崩溃,甚至更好地重写存储过程,从而使其首先不会出现异常。
Thank you for your assistance! 谢谢您的帮助!
Do what Eric said: 照埃里克的话做:
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
I suggest you to use this kind of query instead of yours that will handle NULL values and Zero values: 我建议您使用这种查询而不是将要处理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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.