Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert null value in Database through parameterized query

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.

like image 280
Django Anonymous Avatar asked May 23 '13 14:05

Django Anonymous


People also ask

How do you add a NULL to a database?

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.

How do you set data to NULL in SQL?

If you've opened a table and you want to clear an existing value to NULL, click on the value, and press Ctrl + 0 .

How do I write a parameterized query in SQL?

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 .

How do you insert a NULL value?

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);


2 Answers

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

like image 188
Kevin Kunderman Avatar answered Oct 05 '22 23:10

Kevin Kunderman


Use DBNull.Value

if (dttm.HasValue)
{
    cmd.Parameters.AddWithValue("@dtb", dttm);
}
else
{
    cmd.Parameters.AddWithValue("@dtb", DBNull.Value)
}
like image 39
Carlos Landeras Avatar answered Oct 05 '22 23:10

Carlos Landeras