Monday, December 10, 2012

How to show raiserror message in c#


CREATE PROCEDURE [dbo].[uspGetProductFromProductID] 
@productID int
AS
BEGIN
    SET NOCOUNT ON;
    SELECT * FROM Production.Product WHERE ProductID = @productID
 IF @@ROWCOUNT = 0
  RAISERROR('Unknown ProductID: %d', 16, 1, @productID) WITH NOWAIT
END;
GO

The c# code was as follows:

     SqlDataReader reader = null;
     SqlConnection conn = new SqlConnection("Data Source=ps3119; Initial Catalog=Adventureworks; Integrated Security=SSPI");
            SqlCommand cmd = new SqlCommand("uspGetProductFromProductID", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter productID = cmd.Parameters.Add("@productID", SqlDbType.Int);
            productID.Direction = ParameterDirection.Input;
            productID.Value = 100;
            try
            {
                conn.Open();
                reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (SqlException sqlex)
            {
                conn.Close();
                MessageBox.Show(sqlex.Message);
            }
            catch (Exception ex)
            {
                conn.Close();
                MessageBox.Show(ex.Message);            
            }

ProductID 100 did not exist in the table, and hence I was expecting that the "Unknown ProductID" exception will be thrown. But it wasn't.

Apparently, if a resultset (empty or not) is returned from the stored procedure, the exception thrown by RAISERROR are not 'seen' in c# code.





 ----------------------------------------
The RaiseError will actually throws SqlException in .NET. Therefore you can get the RaiseError message from the SqlException object in the catch block. 
try
 
{ 
    // Write your data access code here 
} 
catch (SqlException e) 
{ 
    string errorMessage =  e.Message; 
     int errorCode =  e.ErrorCode; 
}

No comments:

Post a Comment