Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a boolean type into a bit parameter type in C# and MS SQL Server

I have a C# method that accepts a clientId (int) and hasPaid (boolean) that represents if the client has paid or not. The MS SQL Server stored procedure expects a BIT value (1 or 0) for the @HasPaid parameter yet the method expects a boolean type (true/false) for hasPaid. Will the ADO.NET code take care of converting the boolean to a bit type for SQL Server or do I need to convert the value of hasPaid into a 1 or 0?

public void UpdateClient(int clientId, bool hasPaid)
{
    using (SqlConnection conn = new SqlConnection(this.myConnectionString))
    {
        using (SqlCommand sqlCommand = new SqlCommand("uspUpdatePaymentStatus", conn))
        {
            sqlCommand.CommandType = CommandType.StoredProcedure;
            sqlCommand.Parameters.AddWithValue("@ClientID", clientId);
            sqlCommand.Parameters.AddWithValue("@HasPaid", hasPaid);
            sqlCommand.Connection.Open();
            var rowsAffected = sqlCommand.ExecuteNonQuery();
        }
    }
}
like image 561
webworm Avatar asked Jun 25 '15 15:06

webworm


1 Answers

When working with SQL parameters I find AddWithValue's auto detection feature of the type too unreliable. I find it better to just call Add a explicitly set the type, Add also returns the new parameter it creates from the function call so you can just call .Value on it afterward.

public void UpdateClient(int clientId, bool hasPaid)
{
    using (SqlConnection conn = new SqlConnection(this.myConnectionString))
    {
        using (SqlCommand sqlCommand = new SqlCommand("uspUpdatePaymentStatus", conn))
        {
            sqlCommand.CommandType = CommandType.StoredProcedure;
            sqlCommand.Parameters.Add("@ClientID", SqlDbType.Int).Value = clientId;
            sqlCommand.Parameters.Add("@HasPaid", SqlDbType.Bit).Value = hasPaid;
            sqlCommand.Connection.Open();
            var rowsAffected = sqlCommand.ExecuteNonQuery();
        }
    }
}

Using the correct type is doubly important when using stored procedures and it is expecting a specific type, I just got in to the habit of always doing it this way.

like image 153
Scott Chamberlain Avatar answered Sep 22 '22 05:09

Scott Chamberlain