【发布时间】: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