In my Create
method, I am using a stored procedure to INSERT INTO
my SQL Server database. Sometimes, fields such as Comment
will be left blank. However, it does not work as I wished.
Firstly, this is how my method looks like:
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);
.....................
When task.Condition
is null, command.ExecuteNonQuery();
gets the following error:
: 'Procedure or function 'CreateTask' expects parameter '@Condition', which was not supplied.'
However, the columns in the table are set to allow null values.
The stored procedure also looks like this:
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
Therefore, what should I tweak in order to allow the stored procedure to get null values?
Try this to assign DBNull.Value
to the SqlParameter
if the data is null and you want to insert null
into the database:
parameter = new SqlParameter
{
ParameterName = "@Condition",
Value = (object)task.Condition ?? DBNull.Value,
SqlDbType = SqlDbType.NVarChar
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.