I am developing windows application in C# with SQL Server as backend. I have to display the error message generated in stored procedure, which is handled in try catch block, to the application. It is working fine if we use ExecuteNonQuery()
. The stored procedure will return one ID so I am using ExecuteScalar()
and that error message from the catch block is not displaying.
For ExecuteScalar
also the error will display if we remove the try catch block.
It will not display in client side.
begin
begin try
select 1/0
select 10
end try
begin catch
raiserror (' Some Error Message', 16, 10)
end catch
end
It will display in client side.
begin
select 1/0
raiserror (' Some Error Message', 16, 10)
select 10
end
Kindly provide a solution.
In order to ensure SqlExceptions are detected, all result sets must be consumed by the client. ExecuteScalar()
returns only the first row/column of the result but does not consume the remainder of the results, so the exception is not raised by the client API.
This example code will raise the error by avoiding ExecuteScalar()
and consuming all results:
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(sqlBatchText, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
scalarIntResult = reader.GetInt32(0);
}
while (reader.Read()) { }; //consume remainder of first result
while (reader.NextResult()) { }; //consume subsequent results
}
Console.WriteLine("{0} rows read", rowCount);
}
}
catch
{
throw;
}
Below are common cases where undetected SqlExceptions may occur. If a defensive programming technique like the above is not employed, it is important to code T-SQL to ensure these scenarios do not occur.
See this article for more details.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.