Error while passing DBNull to SqlParameter - c#

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;

Related

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

Difference between DbNull.Value and DbNull.Value.ToString()

I wanted to learn which usage is true?
if(!string.IsNullOrEmpty(parentID))
cmd.Parameters.Add(new SqlParameter("#ParentSesID", parentID));
else
cmd.Parameters.Add(new SqlParameter("#ParentSesID", DBNull.Value));
OR
if(!string.IsNullOrEmpty(parentID))
cmd.Parameters.Add(new SqlParameter("#ParentSesID", parentID));
else
cmd.Parameters.Add(new SqlParameter("#ParentSesID", DBNull.Value.ToString()));
cmd.Parameters.Add(new SqlParameter("#ParentSesID", parentID));
This is passing a parentID to parameter #ParentSesID.
cmd.Parameters.Add(new SqlParameter("#ParentSesID", DBNull.Value));
is passing a null value to parameter.
cmd.Parameters.Add(new SqlParameter("#ParentSesID", DBNull.Value.ToString()));
is passing equal to string.Empty, which is not allowed in numerical data types.
cmd.Parameters.Add(new SqlParameter("#ParentSesID", null);
is same as ignoring the parameter.
So when you need to pass null to SP you've to pass DBNull.Value.
This one: cmd.Parameters.Add(new SqlParameter("#ParentSesID", DBNull.Value)); is a correct, in case the field you are writing to can accept NULL value in database.
This one: cmd.Parameters.Add(new SqlParameter("#ParentSesID", DBNull.Value.ToString())); if the field is a, say, VARCHAR, and does not accept NULL, but you want to indicate in some way an absence of value in that field, so you write inside your application specific "no value" value. So your application knows, if it founds that value in the field, that means: no value.
DBNull.Value.ToString() will return empty string, so I think
cmd.Parameters.Add(new SqlParameter("#ParentSesID", DBNull.Value));
is a good approach and here the only approach
see here:
http://ideone.com/iGo1Jh

Sending null parameters to Sql Server

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

cmd.Parameters.AddWithValue("#param1",param1 ?? DbNull.Value)

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

Passing DBNull.Value and Empty textbox value to database [duplicate]

This question already has answers here:
How do I Parameterize a null string with DBNull.Value clearly and quickly
(8 answers)
Closed 8 years ago.
I have some textboxes on my page which can be empty because they are optional and I have this DAL code
parameters.Add(new SqlParameter("#FirstName", FirstName));
parameters.Add(new SqlParameter("#LastName", LastName));
parameters.Add(new SqlParameter("#DisplayName", DisplayName));
parameters.Add(new SqlParameter("#BirthDate", BirthDate));
parameters.Add(new SqlParameter("#Gender", Gender));
Any of those fields can be empty. The problem is when they are empty I receive Procedure XXX requires #FirstName which was not supplied
Then I changed my code to
parameters.Add(new SqlParameter("#FirstName", String.IsNullOrEmpty(FirstName) ? DBNull.Value : (object)FirstName));
parameters.Add(new SqlParameter("#LastName", String.IsNullOrEmpty(LastName) ? DBNull.Value : (object) LastName));
parameters.Add(new SqlParameter("#DisplayName", String.IsNullOrEmpty(DisplayName) ? DBNull.Value : (object) DisplayName));
parameters.Add(new SqlParameter("#BirthDate", BirthDate.HasValue ? (object)BirthDate.Value : DBNull.Value));
parameters.Add(new SqlParameter("#Gender", String.IsNullOrEmpty(Gender) ? DBNull.Value : (object) Gender));
But this looks messy to me especially the casting to object because ternary statement requires both value to be the same type.
Why is empty string or null string not treated NULL in the database? If I have to convert this to DBNull.Value is there a cleaner way? Saving the value as empty string in the database could have helped but query for NULL in the database will get messy too
Please give your advice on common practices or something close to that.
First, there are 2 more handy overloads:
command.Parameters.Add("#name").Value = value;
or
command.Parameters.AddWithValue("#name", value);
Personally I use the following extension method:
public static object DbNullIfNull(this object obj)
{
return obj != null ? obj : DBNull.Value;
}
command.Parameters.AddWithValue("#name", value.DbNullIfNull());
or
public static object DbNullIfNullOrEmpty(this string str)
{
return !String.IsNullOrEmpty(str) ? str : (object)DBNull.Value;
}
A little re-factoring might make code less messy. Try this
dbParams.Add(SetDBNullIfEmpty("#FirstName", FirstName));
dbParams.Add(SetDBNullIfEmpty("#LastName", LastName));
dbParams.Add(SetDBNullIfEmpty("#DisplayName", DisplayName));
dbParams.Add(SetDBNullIfEmpty("#BirthDate", BirthDate));
dbParams.Add(SetDBNullIfEmpty("#Gender", Gender));
private SqlParameter SetDBNullIfEmpty(string parmName, string parmValue)
{
return new SqlParameter(parmName, String.IsNullOrEmpty(parmValue) ? DBNull.Value : (object)parmValue));
}
You can default the parameters in the stored procedure, making them optional.
create procedure XXX
(
#FirstName nvarchar(50) = null,
#LastName nvarchar(50) = null,
...
)

Categories