因此,首先是我的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
問題是,如果沒有高通的學生,我會得到一個零除異常。尋找有關如何捕獲此異常的建議,以便程序不會崩潰,或者甚至更好地重新編寫存儲過程,以免它首先出現異常。
謝謝您的協助!
選擇計數成存儲過程中的變量,如果計數爲零,則返回您認爲應該返回的任何內容,而不是執行計算。 –
這將容易受到SQL注入攻擊。您應該使用參數化查詢。 –
謝謝Eric J.,現在有效=) –