Friday, January 11, 2013

Raise Error in sql


USE [AdventureWorks]
GO
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);            
            }

No comments:

Post a Comment