简体   繁体   English

将NULL值分配给SqlParameter的最佳方法

[英]Best method of assigning NULL value to SqlParameter

I have a number of optional input parameters I am using in a C# class method. 我在C#类方法中使用了许多可选的输入参数。 Since the optional syntax creates a value of '0' when the parameter is not used, the SQL insert command I call in the method winds up inserting as such. 由于可选语法在未使用参数时会创建值“0”,因此我在方法中调用的SQL插入命令将逐渐插入。 However, I need the command to insert a NULL value instead of a 0 when the parameter is not being used. 但是,我需要命令在不使用参数时插入NULL值而不是0。 What is the best way to accomplish this without using a large amount of 'if' statements? 在不使用大量“if”语句的情况下实现此目的的最佳方法是什么?

Below is the code I am referring to. 以下是我所指的代码。 Is there syntax/a command of some kind that will allow me to specify a NULL value in the SqlParameter declaration? 是否有某种语法/命令允许我在SqlParameter声明中指定NULL值?

public int batchInsert
(
    int id, 
    int outcome, 
    int input = 0, 
    int add = 0, 
    int update = 0,
    int delete = 0,
    int errors = 0, 
    int warnings = 0
)
{
    string sts;
    if (outcome == 0)
    {
        sts = "S";
    }
    else if (outcome == 1)
    {
        sts = "W";
    }
    else
    {
        sts = "E";
    }

    SqlConnection sqlConn = new SqlConnection(this.connString);
    SqlParameter runId = new SqlParameter("@runId", id);
    SqlParameter endTime = new SqlParameter("@endTime", DateTime.Now);
    SqlParameter status = new SqlParameter("@status", sts);
    SqlParameter sqlInput = new SqlParameter("@itemsRead", input);
    SqlParameter sqlAdd = new SqlParameter("@add", add);
    SqlParameter sqlUpdate = new SqlParameter("@update", update);
    SqlParameter sqlDelete = new SqlParameter("@delete", delete);
    SqlParameter sqlError = new SqlParameter("@errors", errors);
    SqlParameter sqlWarning = new SqlParameter("@warnings", warnings);
    SqlParameter result = new SqlParameter("@outcome", results[outcome]);
    SqlCommand sqlComm = new SqlCommand(insertCommand(), sqlConn);

Yes, for the value of the parameter, just use DBNull.Value . 是的,对于参数的值,只需使用DBNull.Value For example: 例如:

SqlParameter sqlError = 
    new SqlParameter("@errors", errors == 0 ? (object)DBNull.Value : errors);

Or write a little helper: 或写一个小帮手:

private object ValueOrDBNullIfZero(int val) {
   if ( val == 0 ) return DBNull.Value;
   return val;
}

Then: 然后:

SqlParameter sqlError = 
    new SqlParameter("@errors", ValueOrDBNullIfZero(errors));

You'd need to check each parameter value and use DBNull.Value send null. 您需要检查每个参数值并使用DBNull.Value发送null。 We have an extension method off object to make this a little easier. 我们有一个object的扩展方法,使这更容易一些。

public static class ObjectExtensions
{
    public static object OptionalParam<T>(this T value, T optionalValue = default(T))
    {
        return Equals(value,optionalValue) ? (object)DBNull.Value : value;
    }
}

Usage: 用法:

var sqlInput = new SqlParameter("@itemsRead", input.OptionalParam());

Or if you want to consider a non-default, arbitrary value as the default value: 或者,如果要将非默认值,任意值视为默认值:

var sqlInput = new SqlParameter("@itemsRead", input.OptionalParam(-1));

这是为sql参数指定Null值的最简单方法

            command.Parameters.AddWithValue("@Comment", string.IsNullOrEmpty(comment) ? (object)DBNull.Value : comment);   

Consider using the Nullable(T) structure available. 考虑使用可用的Nullable(T)结构。 It'll let you only set values if you have them, and your SQL Command objects will recognize the nullable value and process accordingly with no hassle on your end. 如果你拥有它们,它将只允许你设置值,并且你的SQL Command对象将识别可空值并相应地处理,而不会有麻烦。

with small helper class we can create extenction method to add DBNull.Value to sqlparameter 使用小帮助器类,我们可以创建extenction方法将DBNull.Value添加到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. 如果您将null作为值分配或传递给sqlparameter,则此extenction方法将自动将其转换为DBNull并重新分配给sqlparameter。

so no need to worry about what the values we are passing dynamically. 所以不必担心我们动态传递的值。

语法短!

  cmd.Parameters.Add(new SqlParameter{SqlValue=username ?? (object)DBNull.Value,ParameterName="usuario" }  );

Another clear way to set a null datetime parameter when necessary 另一种在必要时设置null datetime参数的明确方法

if(obj.myDate == DateTime.MinValue)
{
    aCommand.Parameters.Add("dateParameter", SqlDbType.Date).Value = DBNull.Value;
}
else
{
    aCommand.Parameters.Add("dateParameter", SqlDbType.Date).Value = obj.myDate ;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM