C# 将null参数传递给存储过程
在我的C# 将null参数传递给存储过程,c#,sql-server,asp.net-core,C#,Sql Server,Asp.net Core,在我的Create方法中,我使用存储过程插入到我的SQL Server数据库中。有时,注释等字段将留空。然而,它并没有像我所希望的那样起作用 首先,我的方法是这样的: using (SqlConnection connection = new SqlConnection(connectionString)) { string sql = "CreateTask"; using (SqlCommand command = new S
Create
方法中,我使用存储过程插入到我的SQL Server数据库中。有时,注释
等字段将留空。然而,它并没有像我所希望的那样起作用
首先,我的方法是这样的:
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
因此,为了允许存储过程获取空值,我应该调整什么?如果数据为空,并且希望将null
插入数据库,请尝试将DBNull.Value
分配给SqlParameter
:
parameter = new SqlParameter
{
ParameterName = "@Condition",
Value = (object)task.Condition ?? DBNull.Value,
SqlDbType = SqlDbType.NVarChar
};
将存储过程的参数声明为可选。如果数据值为null,则可以改为赋值DBNull.value
。@Crowcoder,如果我使用,例如,command.Parameters.Add(parameter,DBNull.value)
,我得到一个错误,说无法从System.DBNull转换为System.Data.SqlDbType
@Questieme,所以不要使用该重载,就像您在示例中设置值时一样。将参数声明为@Condition varchar(450)=null
,如果不使用命令.ParametersAdd
添加参数,则该参数将为空。使用“默认值”或@Yurii建议的可选参数会更好<代码>运算符“??”不能应用于“string”和“DBNull”类型的操作数。
@Luuk不一定。您不能假设您总是希望存储过程参数有一个默认值。@Questieme,我忘了强制转换到对象。如果看起来太黑,您也可以在外部设置它。@Questieme还指出,您可以在存储过程本身中设置默认值,但只有您才能知道这是否是您想要的。它的优点是不需要更改代码。