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();
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With