I have a SqlCommand object that I'm using to update a database table but it doesn't interpret my null values correctly.
Here is the SQL:
UPDATE dbo.tbl
SET param1 = #param1,
param2 = #param2,
param3 = #param3,
param4 = #param4,
param5 = #param5,
param6 = #param6,
param7 = #param7,
param8 = #param8,
param9 = #param9,
param10 = #param10
WHERE param11 = #param11
I have tried null coalescing parameters that are nullable like this, but I haven't had any success. Unless otherwise noted, all parameters are strings:
command.Parameters.AddWithValue("#param1", param1 ?? DBNull.Value);
command.Parameters.AddWithValue("#param2", param2 ?? DBNull.Value);
command.Parameters.AddWithValue("#param3", param3 ?? DBNull.Value);
command.Parameters.AddWithValue("#param4", param4 ?? DBNull.Value);
command.Parameters.AddWithValue("#param5", param5 ?? DBNull.Value);
// param6 is nullable type DateTime?
command.Parameters.AddWithValue("#param6", param6 ?? DBNull.Value);
command.Parameters.AddWithValue("#param7", param7 ?? DBNull.Value);
// param8 is nullable type DateTime?
command.Parameters.AddWithValue("#param8", param8 ?? DBNull.Value);
command.Parameters.AddWithValue("#param9", param9 ?? DBNull.Value);
// param10 nullable type float?
command.Parameters.AddWithValue("#param10", param10 ?? DBNull.Value);
command.Parameters.AddWithValue("#param11", param11 ?? DBNull.Value);
I get an exception like this:
The parameterized query '(#param1 nvarchar(4000),#param2 nvarchar(4000),#param3 nvarc' expects the parameter '#param4', which was not supplied.
I've also tried looping through each parameter after they've been added to the SqlCommand object to set DbNull.Value if the parameter value is null like this:
foreach (SqlParameter parameter in command.Parameters)
{
if (parameter.Value == null)
{
parameter.Value = DBNull.Value;
}
}
However, this approach is causing the exception:
String or binary data would be truncated.
The statement has been terminated.
What is the best practice for passing null parameters to a SqlCommand? I don't simply want to pass in default values if they're null since the database schema allows null values.
Try this :
command.Parameters.AddWithValue("#param1", param1 ?? Convert.DBNull);
hi try using the following synatx:
command.parameters.add("#ParameterName",DBNull.value);
hope this helps
commandObject.Parameters.AddWithValue("#parameterName",Convert.DBNull);
Related
I am trying to pass null value to SqlParameter if the value of variable vName is null, else pass vName value as shown below
cmd.Parameters.Add(new SqlParameter("#NAME", SqlDbType.VarChar)).Value = vName ? null : DBNull.Value;
but I get an error
Cannot implicitly convert type 'string' to 'bool'
I searched and found that I have to use AgeItem.AgeIndex but I got error that says
The name 'AgeItem' does not exist in the current context
cmd.Parameters.Add(new SqlParameter("#NAME", SqlDbType.VarChar)).Value =(object)AgeItem.AgeIndex ?? DBNull.Value;
vName is a string but you use it like it was a bool: vName ? .... Use vName == null ? ...:
cmd.Parameters.Add(new SqlParameter("#NAME", SqlDbType.VarChar)).Value =
vName == null ? DBNull.Value : (Object)vName;
IMHO much cleaner:
if (vName != null)
cmd.Parameters.AddWithValue("#NAME",vName);
else
cmd.Parameters.AddWithValue("#Name",null);
Code should be change as follow
cmd.Parameters.Add(new SqlParameter("#NAME", SqlDbType.VarChar)).Value!= null ? vName: DBNull.Value;
My query returns false when some values are null, but my table allows Null values.
What did I do wrong?
cmd.CommandText ="Insert into BusinessTbl(BName,BAddress,BEmail,BMobile,BPhone,Cat_Id)" +
"values(#bname,#baddress,#bemail,#bmobile,#bphone,#catid)";
cmd.Parameters.AddWithValue("#bname", b.BusinessName);
cmd.Parameters.AddWithValue("#name", b.BusinessAddress);
cmd.Parameters.AddWithValue("#bemail", b.BusinessEmail);
cmd.Parameters.AddWithValue("#bmobile", b.BusinessMobile);
cmd.Parameters.AddWithValue("#bphone", b.BusinessPhone);
cmd.Parameters.AddWithValue("#catid", b.ddlbcategory);
con.ExecuteNonQuery(cmd);
My Table
This is a vexing feature of ADO.NET parameters; basically:
cmd.Parameters.AddWithValue("#bname", ((object)b.BusinessName) ?? DBNull.Value);
cmd.Parameters.AddWithValue("#name", ((object)b.BusinessAddress) ?? DBNull.Value);
// etc
should fix you. If the .Value is null, the parameter isn't sent - it needs to be DBNull.Value. Alternatively, a tool like "Dapper" helps avoid this pain:
con.Execute(#"Insert into BusinessTbl(BName,BAddress,BEmail,BMobile,BPhone,Cat_Id)
values(#bname,#baddress,#bemail,#bmobile,#bphone,#catid)",
new { bname = b.BusinessName, ... , catid = b.ddlbcategory });
(which will parameterize correctly, including the nulls)
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);
I have int? type value which can be either null or have some value. I want to execute a insert statement using parametrized query to insert accordingly.
int? val1=null;
SqlCeCommand cmd;
string insert = "insert into table(col1)values(#col_1)";
cmd = new SqlCeCommand();
cmd.CommandText = insert;
cmd.Parameters.AddWithValue("#col_1", val1 ?? Convert.ToInt32(DBNull.Value)));
cmd.Connection = cn1;
cn1.Open();
cmd.ExecuteNonQuery();
cn1.Close();
This code throws format exception error. I even tried
cmd.Parameters.AddWithValue("#col_1", (!val1.HasValue) ? val1 : Convert.ToInt32(DBNull.Value));
How shld it b done?
no need to convert if null set DBNull
cmd.Parameters.AddWithValue("#col_1", (object)val1 ??DBNull.Value);
I would believe that changing the line to the following should work:
cmd.Parameters.AddWithValue("#col_1", val1 ?? DBNull.Value);
Since this would set the parameter value to an object type.
If that fails for some reason try to cast the result to an object like this:
cmd.Parameters.AddWithValue("#col_1", (object)(val1 ?? DBNull.Value));
But this should not be necessary.
Edit:
Actually, this should work:
cmd.Parameters.AddWithValue("#col_1", val1 ?? (object)DBNull.Value);
You Should change add parameter code like this:
if (val1.HasValue)
{
cmd.Parameters.AddWithValue("#col_1", val1.Value);
}
else
{
cmd.Parameters.AddWithValue("#col_1", DBNull.Value);
}
When I add the SQL parameter p to the collection I get an InvalidCastException with the message from the post title.
parentId is a nullable integer and a nullable integer in the database.
Why do I get this exception and how can I solve it?
I do not use stored procedures and I have read the similar threads but they did not help me.
var p = new SqlParameter("ParentId", SqlDbType.Int).Value = parentId ?? (object) DBNull.Value;
cmd.Parameters.Add(p);
You aren't adding your new SqlParameter. p is the result of new SqlParameter("ParentId", SqlDbType.Int).Value = parentId ?? (object) DBNull.Value. In other words, p itself is DBNull.Value.
Split the statement in two, like so:
var p = new SqlParameter("ParentId", SqlDbType.Int);
p.Value = parentId ?? (object) DBNull.Value;
cmd.Parameters.Add(p);
Alternatively,
var p = new SqlParameter("ParentId", SqlDbType.Int) { Value = parentId ?? (object) DBNull.Value };
cmd.Parameters.Add(p);
Either would make sure p is the parameter, not the parameter's value.
You need to use:
System.Data.SqlTypes.SqlInt32.Null