Using null while adding SQL parameters - c#

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

Related

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

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;

Null values are not inserted in Allow Nulls colums in C#

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)

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

Test SQL Parameter for null or blank value

I'm performing a simple insert into an SQL database. The query is parametrised but when I call the method which performs this insert I may not always want to populate each parameter.
As follows:
using (var sqlconnection = new SqlConnection(Globals.AFWideSettings.SqlConnectionString))
{
sqlconnection.Open();
using (
var sqlcommand =
new SqlCommand(
"insert into DataActions (afuser, aftable, changetype, originaldata, newdata) values (#afuser, #aftable, #changetype, #originaldata, #newdata);",
sqlconnection))
{
sqlcommand.Parameters.Add(new SqlParameter("afuser", userActions.AfUser));
sqlcommand.Parameters.Add(new SqlParameter("aftable", userActions.AfTable));
sqlcommand.Parameters.Add(new SqlParameter("changetype", userActions.ChangeType));
sqlcommand.Parameters.Add(new SqlParameter("originaldata", userActions.OriginalData));
sqlcommand.Parameters.Add(new SqlParameter("newdata", userActions.NewData));
sqlcommand.ExecuteNonQuery();
}
sqlconnection.Close();
}
}
If I was testing for Null information coming out of the database I would do something like:
Id = getRecords.IsDBNull(0) ? -1 : getRecords.GetInt32(0)
Is there a equivalent way of doing this on sqlparameters ? I'm stumped.
(I know I could test each item individually, I just want to be efficient)
Many thanks
Well, you have to populate each parameter because it's in your SQL (unless you want to dynamically remove fields/values which would be messy).
I would just use the NULL coalesce operator (??) when setting the parameter values:
sqlcommand.Parameters.Add(
new SqlParameter("afuser", userActions.AfUser ?? {insert default value here} ));
Okay, so the basic syntax is as follows:
CREATE PROCEDURE NameOfProcedure
/*
I like to put modification history, purpose for the procedure and stuff like that in here.
It's not required though
*/
(
#afuser NVARCHAR(255) DEFAULT NULL
,#aftable INT DEFAULT NULL
Do this for all your variables, I've shown an example of an integer field and an nvarchar field but use whatever the datatype is. The DEFAULT NULL bit is the part that says if no value is specified, use NULL.
)
AS
BEGIN
INSERT INTO DataActions (afuser, aftable, changetype, originaldata, newdata)
VALUES (#afuser, #aftable, #changetype, #originaldata, #newdata)
END
you could do it using the DBNull value
I would recommend using Parameters.AddWithValue() Method for example see the code below
sqlcommand.Parameters.AddWithValue("#afuser", userActions.AfUser ?? (object)DBNull.Value);
MSDN SqlParameterCollection.AddWithValue Method

Categories