c# - 将空参数传递给存储过程
问题描述
在我的方法中,我对我的 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
因此,我应该如何调整以允许存储过程获取空值?
解决方案
如果数据为空并且您想插入数据库,请尝试将此分配DBNull.Value
给:SqlParameter
null
parameter = new SqlParameter
{
ParameterName = "@Condition",
Value = (object)task.Condition ?? DBNull.Value,
SqlDbType = SqlDbType.NVarChar
};
推荐阅读
- java - 在 JSP 中使用复选框时出现索引顺序问题
- reactjs - 在基于 AWS 认证用户的反应导航中使用条件语句
- android - 如何从我在 Android 的服务中运行的 switch case 开始新的活动?
- azure - 如何在 Azure 上运行的 Asp Classic 应用程序上启用身份验证
- authentication - OAuth2授权码流和单页应用
- mysql - Spring JPA 和 MySQL 存储不正确的 LocalDateTime 值
- swift - 如何导航到新视图但删除它与 NavigationView 的连接?
- c# - ATAPI.dll MakeCall 导致 ObjectDisposedException
- python - Roblox 从目录中购买商品
- directus - 如何通过 SQL 查询上传图像?