首页 > 解决方案 > 将空参数传递给存储过程

问题描述

在我的方法中,我对我的 SQL Server 数据库Create使用存储过程。INSERT INTO有时,诸如此类的字段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

因此,我应该如何调整以允许存储过程获取空值?

标签: c#sql-serverasp.net-core

解决方案


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

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

推荐阅读