【问题标题】:Passing null parameter to the stored procedure将空参数传递给存储过程
【发布时间】:2019-12-21 14:56:12
【问题描述】:

在我的Create 方法中,我使用存储过程来INSERT INTO 我的SQL Server 数据库。有时,Comment 等字段会留空。但是,它并没有像我希望的那样工作。

首先,我的方法是这样的:

using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string sql = "CreateTask";

            using (SqlCommand command = new SqlCommand(sql, connection))
            {
                command.CommandType = CommandType.StoredProcedure;

                .....................

                parameter = new SqlParameter
                {
                    ParameterName = "@Condition",
                    Value = task.Condition,
                    SqlDbType = SqlDbType.NVarChar
                };
                command.Parameters.Add(parameter);
                .....................

task.Condition 为空时,command.ExecuteNonQuery(); 得到以下错误:

: '过程或函数'CreateTask'需要参数'@Condition',但未提供。'

但是,表中的列设置为允许空值。

存储过程也如下所示:

    ALTER PROCEDURE [dbo].[CreateTask]
    @Name        NVARCHAR(50),
    @IsGate   BIT,
    @Condition Varchar(450),
    @Precondition       Varchar(450),
    @Comments       Varchar(450),
    @StartDate       DateTime,
    @EndDate       DateTime,
    @AssignedTo    Nvarchar(450),
    @PhaseId int 
AS
BEGIN
    Insert Into dbo.Tasks (Name, IsGate, Condition, Precondition, Comments, StartDate, EndDate, AssignedTo, PhaseId, InProgress, Finished, Aborted) Values (@Name, @IsGate, @Condition, @Precondition, @Comments, @StartDate, @EndDate, @AssignedTo, @PhaseId, '0', '0', '0')
END

因此,我应该如何调整才能让存储过程获得空值?

【问题讨论】:

  • 将存储过程的参数声明为可选。 For reference
  • 如果数据的值为空,您可以指定DBNull.Value
  • @Crowcoder 例如,如果我使用command.Parameters.Add(parameter, DBNull.Value);,我会收到一条错误消息cannot convert from System.DBNull to System.Data.SqlDbType
  • @Questieme 所以不要使用那个重载,就像在你的例子中设置Value一样。
  • 声明参数为@Condition varchar(450) = null,如果不添加command.ParametersAdd参数则为NULL。

标签: c# sql-server asp.net-core


【解决方案1】:

如果数据为空并且您想将null 插入数据库,请尝试将DBNull.Value 分配给SqlParameter

parameter = new SqlParameter
{
    ParameterName = "@Condition",
    Value = (object)task.Condition ?? DBNull.Value,
    SqlDbType = SqlDbType.NVarChar
};

【讨论】:

  • @Yurii 建议的“默认”或可选参数要好得多!
  • Operator '??' cannot be applied to operands of type 'string' and 'DBNull'
  • @Luuk 不一定。你不能假设你总是想要一个存储过程参数的默认值。
  • @Questieme appologies,我忘了投反对票。如果看起来太 hacky,你也可以将它设置在外面。
  • @Questieme 还指出,您可以在存储过程本身中设置默认值,但只有您才能知道这是否是您想要发生的。它的优点是不需要更改代码。
猜你喜欢
  • 2016-04-05
  • 1970-01-01
  • 2013-06-17
  • 2012-10-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多