1

最初に私の 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

問題は、ハイパスの生徒がいない場合、ゼロ除算の例外が発生することです。プログラムがクラッシュしないようにこの例外をキャッチする方法、またはそもそも例外が発生しないようにストアド プロシージャを書き直す方法についての提案を探しています。

ご協力いただきありがとうございます!

4

2 に答える 2

2

エリックが言ったことを実行します。

    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 

于 2015-05-20T00:18:22.877 に答える
0

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
于 2015-05-20T05:02:20.130 に答える