I have a datetime
datatype : dttm
Also the database field type is datatime
Now I am doing this:
if (dttm.HasValue)
{
cmd.Parameters.AddWithValue("@dtb", dttm);
}
else
{
// It should insert null value into database
// through cmd.Parameters.AddWithValue("@dtb", _____)
}
How can this be done.
You can insert NULL value into an int column with a condition i.e. the column must not have NOT NULL constraints. The syntax is as follows. INSERT INTO yourTableName(yourColumnName) values(NULL); To understand the above syntax, let us first create a table.
If you've opened a table and you want to clear an existing value to NULL, click on the value, and press Ctrl + 0 .
Declare statements start with the keyword DECLARE , followed by the name of the parameter (starting with a question mark) followed by the type of the parameter and an optional default value. The default value must be a literal value, either STRING , NUMERIC , BOOLEAN , DATE , or TIME .
You also can specify the NULL keyword in the VALUES clause to indicate that a column should be assigned a NULL value. The following example inserts values into three columns of the orders table: INSERT INTO orders (orders_num, order_date, customer_num) VALUES (0, NULL, 123);
This can be done using the null-coalescing operator: if the value of dttm is null the DBNull.Value will be inserted otherwise the value of dttm will be used
cmd.Parameters.AddWithValue("@dtb", dttm ?? (object) DBNull.Value);
This will eliminate the need for the if statment
Use DBNull.Value
if (dttm.HasValue)
{
cmd.Parameters.AddWithValue("@dtb", dttm);
}
else
{
cmd.Parameters.AddWithValue("@dtb", DBNull.Value)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With