C# INSERT to SQL method exception when DateTime parameter is null - c#

One of my parameter looks like this:
cmd.Parameters.Add("#last_sign_in_at", SqlDbType.DateTime).Value = user.last_sign_in_at;
I know that User has null value in last_sign_in_at. Database accept nulls for this column but I get an exception:
SqlException: The parameterized query '(#id int,#name nvarchar(18),#username nvarchar(11),#state nvarch' expects the parameter '#last_sign_in_at', which was not supplied.

You should be using DBNull.Value:
cmd.Parameters.Add("#last_sign_in_at", SqlDbType.DateTime).Value = (object)user.last_sign_in_at ?? (object)DBNull.Value;
Casting to object here is just for operator ?? to not complain about different types

When using raw .net framework, I've always had to use the value DBNull.Value.
cmd.Parameters.Add("#last_sign_in_at", SqlDbType.DateTime).Value = DBNull.Value;

Related

SQLCommand.CreateParameter.Value = DBNull.Value not returning results

I have code that creates a Null parameter like this
p = cmd.CreateParameter();
p.DbType = DbType.Int32;
p.ParameterName = strName;
p.Value = DBNull.Value;
cmd.Parameters.Add(p);
when I insert a record the SQLValue is set to {Null}
And the record is properly created with a Null value for the column.
When I select a record to try and retrieve a record with a Null value setting the parameter using the same approach above..once again the SQLValue for the parameter is {Null}
So same code same set up...but now it does not return the record. I cant retrieve any records when I want to create a parameter with a null value (p.Value = DBNull.Value;) . I get nothing back.
I know its not the query because if I change the parameter to one with a value I get that record back. Is there something I am missing to set the parameter to look for a null value? Everything I have seen has said to just do it that way.
As requested below is the query
Select * from view_full_class_nests
where parent_interface_class_pk = #parent_interface_class_pk
Also as noted this query works fine if the paramter is set with a value...only fails to retrieve if the value is DBNull.Value
DanD below provided useful link that gave me my answer
Need the query to be Select * from view_full_class_nests
where parent_interface_class_pk = #parent_interface_class_pk or #parent_interface_pk Is Null
You can't compare NULL in your where clause:
From https://msdn.microsoft.com/en-us/library/ms172138(v=vs.100).aspx:
Because null is considered to be unknown, two null values compared to each other are not considered to be equal. In expressions using arithmetic operators, if any of the operands is null, the result is null as well.
You will have to use ISNULL operator, see below for a previous answer that may help you:
Null value parameters in where clause in ado.net

SQLCommand SqlParameter Default Column Value in UPDATE C#

How to set Default Value as Value of SqlCommand SqlParameter?
SqlCommand is the class contained in System.Data.SqlClient
My Schema does not accept DBNull.Value as value
SqlCommand command = new SqlCommand();
command.Parameters.Add(new SqlParameter("column_1", SqlDbType.VarChar, 1) { Value = DBNull.Value });
As lboshuizen points out, if your "schema" isn't taking null, or the parameter of the stored procedure or query cannot be null, trying to give it a null value will likely fail. In this case, you need to see why you are trying to set it to null if you know it doesn't accept it. I would surmise an empty string as opposed to null would work, or something else that is sensible.
The SqlParameterCollection property Parameters has an AddWithValue method:
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx
You can simply insert null and that will be handled for you:
command.Parameters.AddWithValue("#parameter", null);
If you cannot provide a null, you can provide something like an empty string:
command.Parameters.AddWithvalue("#parameter", "");
You also very rarely need to specify the data type using this mechanism.
If the schema doesn't accept null it indicates that the column is mandatory and requires a sensible value.
Using a default value for a column is a property of the schema.
So either alter the schema to provide a default.
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
Choose a valid (not null) default value in your application code and use it as a value in the parameter.
const string default = "unknown";
...
SqlCommand command = new SqlCommand();
command.Parameters.Add(new SqlParameter("column_1", SqlDbType.VarChar, 1)
{ Value = default });
Note: Changing the schema to accept NULL is considered cheating :-)

Using null while adding SQL parameters

I would like to add some null's to table:
command.CommandText =
"INSERT into clients (Addres, companyID) VALUES (#Addres, #companyID) ; select SCOPE_IDENTITY();";
command.Parameters.AddWithValue("#Addres", null);
command.Parameters.AddWithValue("#companyID", null);
Table dessign allows null's. Why I have this error then?
The parameterized query '(#Addres nvarchar(4000),#companyID nvarchar(4000))INSERT into cl' expects the parameter '#Addres', which was not supplied.
Use DBNull.Value instead.
command.Parameters.AddWithValue("#Addres", DBNull.Value);
command.Parameters.AddWithValue("#companyID", DBNull.Value);
You have to use DBNull class for null values in SQL. Your code will be like this:
command.Parameters.AddWithValue("#Addres", DBNull.Value);
command.Parameters.AddWithValue("#companyID", DBNull.Value);
You can use System.Data.SqlTypes.SqlString.Null
command.Parameters.AddWithValue("#Addres", System.Data.SqlTypes.SqlString.Null);
command.Parameters.AddWithValue("#companyID", System.Data.SqlTypes.SqlString.Null);
Read: Handling Null Values
DBNull.Value can be used for any type as opposed to SqlTypes.
It can be handy to make the code more readable and type-safe, for example:
var addrVal = new System.Data.SqlTypes.SqlString(someAddress);
// ...
if (condition) addrVal = System.Data.SqlTypes.SqlString.Null;
command.Parameters.AddWithValue("#Addres", addrVal);

Setting date value in a database field when input in Null

I am trying to set an condition when setting up parameter for a database field so that if the receiving value is null then it should set it to current date
cmd.Parameters.AddWithValue("#DatePlannedEnd", SqlDbType.NVarChar).Value = pm.DatePlannedEnd != null ? pm.DatePlannedEnd : DateTime.Now.Date;
I get error:
Type of conditional expression can not be determined because there is no implicit conversion between string and System.Date.Time
DatePlannedEnd is a Date field in the database. Any idea what will be the right way to achieve what I am trying to do?
You are mixing up Add and AddWithValue. The whole point of AddWithValue is that you provide the value, not the type, of the parameter. The type is inferred from the value. If you're going to set the Value property explicitly then call Add, not AddWithValue.
Apart from that, why are you specifying the type as NVarChar and then assigning a DateTime as the value? If the data type in the database is date then the SqlDbType should be Date, not NVarChar. If you use AddWithValue though, that will be inferred.
You can try checking the value first before submitting against the database :)
if (pm.DatePlannedEnd == null) {
pm.DatePlannedEnd = DateTime.Now.Date.ToString();
}
You can't return two different types from a ternary expression.
You're adding DateTime.Now as a date, but your parameter type is a string. Convert it to a string first.
Also, use one method or the other of adding parameters, not a combination of both.
var datePlannedEnd = pm.DatePlannedEnd ?? DateTime.Now.Date.ToString();
cmd.Parameters.Add("#DatePlannedEnd", SqlDbType.NVarChar);
cmd.Parameters["#DatePlannedEnd"].Value = datePlannedEnd;
Or:
cmd.Parameters.AddWithValue("#DatePlannedEnd", datePlannedEnd);
And if you have any control over the database, think about altering that column type to be a date instead of a string. That way, you won't have to parse a string back into a valid DateTime whenever you get the value back out of the database.

C# - ODP.NET and ora-01475 must reparse cursor to change bind variable datatype

I'm getting ora-01475 whenever I try to insert a null value in a column (of type DateTime) after some records have already been inserted that have real date values.
I'm using the OracleParameter constructor that takes the name and the value as an object (I assume the data type is then implied from the datatype of the object), but since sometimes the value of my parameter is null, it's being set as a String, therefore throwing this error.
I don't want to use the constructor that takes the datatype explicitly because I use reflection heavily to build the OracleCommand object and its parameters.
How can I reparse the cursor (as the error suggests) if I find this situation?
Has anyone else run into this and has a solution?
Have you tried to use nullable types?
DateTime? myDate;
//Code to set myDate value...
string sql = "[your SQL]"
using (OracleCommand command = new SqlCommand(sql, cn))
{
OracleParameter param = new OracleParameter(":Name",myDate);
command.Paerameters.add(param);
command.ExecuteNonQuery();
}

Categories