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
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.