1

因此,首先是我的C#代碼,然後是存儲過程。SQL Server&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 

問題是,如果沒有高通的學生,我會得到一個零除異常。尋找有關如何捕獲此異常的建議,以便程序不會崩潰,或者甚至更好地重新編寫存儲過程,以免它首先出現異常。

謝謝您的協助!

+5

選擇計數成存儲過程中的變量,如果計數爲零,則返回您認爲應該返回的任何內容,而不是執行計算。 –

+1

這將容易受到SQL注入攻擊。您應該使用參數化查詢。 –

+0

謝謝Eric J.,現在有效=) –

回答

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 

+0

非常感謝LeMara,它的魅力! –

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