I was previously taught today how to set parameters in a SQL query in .NET in this answer (click).
Using parameters with values are fine, but when I try to set a field in the database to null I'm unsuccessful. Either the method thinks I am not setting a valid parameter or not specifying a parameter.
e.g.
Dim dc As New SqlCommand("UPDATE Activities SET [Limit] = @Limit WHERE [Activity] = @Activity", cn) If actLimit.ToLower() = "unlimited" Then ' It's not nulling :( dc.Parameters.Add(New SqlParameter("Limit", Nothing)) Else dc.Parameters.Add(New SqlParameter("Limit", ProtectAgainstXSS(actLimit))) End If
Is there something I'm missing? Am I doing it wrong?
The rule for assigning NULL values to variables or table columns is simple: Use keyword "NULL" directly as normal values. Specificly, "NULL" can be used in SET statements to assign NULL values to variables. "NULL" can be used in SET clauses in UPDATE statements.
You have to check the value returned by ExecuteScalar() for null and only call Convert. ToInt32() if it is not null.
When SET CONCAT_NULL_YIELDS_NULL is ON, concatenating a null value with a string yields a NULL result. For example, SELECT 'abc' + NULL yields NULL . When SET CONCAT_NULL_YIELDS_NULL is OFF, concatenating a null value with a string yields the string itself (the null value is treated as an empty string).
When you concatenate any string with a NULL value, it will result in NULL. To avoid this, you can use the COALESCE function. The COALESCE function returns the first non-Null value. So, when there is a value in the column that is not null, that will be concatenated.
you want DBNull.Value.
In my shared DAL code, I use a helper method that just does:
foreach (IDataParameter param in cmd.Parameters) { if (param.Value == null) param.Value = DBNull.Value; }
I use a SqlParameterCollection
extension method that allows me to add a parameter with a nullable value. It takes care of converting null
to DBNull
. (Sorry, I'm not fluent in VB.)
public static class ExtensionMethods { public static SqlParameter AddWithNullable<T>(this SqlParameterCollection parms, string parameterName, T? nullable) where T : struct { if (nullable.HasValue) return parms.AddWithValue(parameterName, nullable.Value); else return parms.AddWithValue(parameterName, DBNull.Value); } }
Usage:
string? optionalName = "Bozo"; cmd.Parameters.AddWithNullable("@Name", optionalName);
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