SQL 服务器和 C# 存储过程和除以零异常

SQL Server & C# Stored Procedure & Divide by Zero Exception

首先是我的 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

问题是,如果没有高分的学生,我将得到除以零的异常。寻找有关如何捕获此异常的建议,以便程序不会崩溃,或者更好地重新编写存储过程,以便它首先不会出现异常。

感谢您的协助!

按照埃里克所说的去做: <pre> 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 </pre>

我建议您使用这种查询而不是您的查询,它将处理 NULL 值和 Zero 值:

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