Best method of assigning NULL value to SqlParameter

前端 未结 7 1384
野的像风
野的像风 2021-01-07 20:53

I have a number of optional input parameters I am using in a C# class method. Since the optional syntax creates a value of \'0\' when the parameter is not used, the SQL inse

7条回答
  •  误落风尘
    2021-01-07 21:11

    with small helper class we can create extenction method to add DBNull.Value to sqlparameter

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Data.SqlClient;
    using System.Data;
    using System.Data.Common;
    
    namespace System.Data.SqlClient
    {
        public static class ExtensionMethods 
    
        {
    
    
    
            public static SqlParameter AddParameter(this SqlParameterCollection parms, SqlParameter param)
            {
                if (param.Value == null)
                {
                    param.Value = DBNull.Value;
                    return parms.Add(param);
                }
                else
                {
                    return parms.Add(param);        
                }
    
            }
    }
    

    usage

    SqlParameter _FraudPackageID = new SqlParameter("@FraudPackageID", System.Data.SqlDbType.BigInt);
     _FraudPackageID.Value = FraudPackageID;
     _FraudPackageID.Direction = System.Data.ParameterDirection.Input;
    
    _cmd.Parameters.AddParameter(_FraudPackageID);
    

    if you assign or pass null as value to sqlparameter this extenction method will automatically converts it to DBNull and reassign to the sqlparameter.

    so no need to worry about what the values we are passing dynamically.

提交回复
热议问题