Set a database value to null with a SqlCommand + parameters

前端 未结 3 1175
情书的邮戳
情书的邮戳 2020-12-15 03:27

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 fie

相关标签:
3条回答
  • 2020-12-15 04:05

    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);
    
    0 讨论(0)
  • 2020-12-15 04:07

    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;
        }
    
    0 讨论(0)
  • 2020-12-15 04:10

    Try setting it to DbNull.Value.

    0 讨论(0)
提交回复
热议问题