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,
...
)
Related
I have this code for executing stored procedure:
var result = await DbContext.Database.ExecuteSqlRawAsync(
"Get_FlightBooking #BookingReferenceNumber, #BM_BKDTFOM, #BM_BKDTTO, #User_Id",
new SqlParameter("#BookingReferenceNumber", model.BookingId == string.Empty ? null : model.BookingId),
new SqlParameter("#BM_BKDTFOM", model.FromDt == string.Empty ? null : model.FromDt),
new SqlParameter("#BM_BKDTTO", model.FromDt == string.Empty ? null : model.FromDt),
new SqlParameter("#User_Id", model.UserId));
This is the stored procedure:
ALTER Proc [dbo].[Get_FlightBooking]
(
#BookingReferenceNumber VARCHAR(50)=NULL,
#BM_BKDTFOM VARCHAR(50)=NULL,
#BM_BKDTTO VARCHAR(50)=NULL,
#User_Id bigint=null
)
as
begin
SELECT distinct BookingID,
BookingReferenceNumber,
Sector,
AirlineCode,
AirlineName,
FROM dbo.Flights AS fb
WHERE (fb.BookingReferenceNumber=#BookingReferenceNumber OR #BookingReferenceNumber IS NULL)
AND((CAST(fb.BookingDate AS DATE)>= CAST(#BM_BKDTFOM AS DATE) OR #BM_BKDTFOM IS NULL) AND (CAST(fb.BookingDate AS DATE)<=CAST(#BM_BKDTTO AS DATE) OR #BM_BKDTTO IS NULL))
AND (fb.UserId=#User_Id or #User_Id=1)
END
Is anyone seeing something wrong in the way how the stored procedure is being executed? When calling the C# code I'm getting this error:
The parameterized query '(#BookingReferenceNumber
nvarchar(4000),#BM_BKDTFOM nvarchar(400' expects the parameter
'#BookingReferenceNumber', which was not supplied.
Any idea what can be wrong?
You need to use DBNull.Value and not null
var result = await DbContext.Database.ExecuteSqlRawAsync(
"UspGet_FlightBooking #BookingReferenceNumber, #BM_BKDTFOM, #BM_BKDTTO, #User_Id",
new SqlParameter("#BookingReferenceNumber", string.IsNullOrWhiteSpace(model.BookingId) ? DNNull.Value : model.BookingId),
new SqlParameter("#BM_BKDTFOM", string.IsNullOrWhiteSpace(model.FromDt) ? DNNull.Value : model.FromDt),
new SqlParameter("#BM_BKDTTO", string.IsNullOrWhiteSpace(model.FromDt) ? DNNull.Value : model.FromDt),
new SqlParameter("#User_Id", model.UserId));
If you cant use C# 9.0 maybe try initialising your SqlParameters like this:
new SqlParameter("#BookingReferenceNumber", System.Data.SqlDbType.NVarChar, 4000)
{ Value = string.IsNullOrWhiteSpace(model.BookingId) ? (object)DBNull.Value : model.BookingId }
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;
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);
This is the signature of my stored procedure:
Create Procedure sp_Member_Account_Select_By_User_And_Membership_Year
(
#Username varchar(150),
#Membership_Year varchar(10)
)
AS
The code in asp.net c#
command.Parameters.Add("#Username", SqlDbType.VarChar,150).Value = vUsername;
command.Parameters.Add("#Membership_Year", SqlDbType.VarChar,10).Value = "2014";
SqlDataReader dr;
dr = command.ExecuteReader();
The error message:
Procedure or function
'sp_Member_Account_Select_By_User_And_Membership_Year' expects
parameter '#Username', which was not supplied.
I have tried different ways of adding parameters, including Addwithvalue, but with no success. What am I missing?
Since you obviously add the parameter to the command, there are two more things that can cause this exception:
Set the command type to CommandType.StoredProcedure:
command.ComandType = CommandType.StoredProcedure;
Set the user name parameter to DBNull.Value if vUsername is null:
command.Parameters.Add("#Username", SqlDbType.VarChar,150).Value = vUsername ?? DBNull.Value;
Could vUsername be null? When you need to pass a null to a stored procedure, you need to pass the constant DBNull.Value rather than null.
Something like
command.Parameters.Add("#Username", SqlDbType.VarChar,150).Value =
(vUsername == null) ? DbNull.Value : (object) vUsername;
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);