How to check if a table field is Empty or NULL? - c#

I have a field in my table (Mssql database), "Name (Varchar(20)) NULL)"
How to read the field, which can be Empty or null?
I do like this:
if (myReader["Name"] != DBNull.Value || myReader["Name"] !=String.Empty)
Is there a built-in c# function to check it ?
(IsNullOrEmpty() ?? It doesn't check Database NULL type ?)

You must test DBNull.Value obligatory
IsNullOrEmpty test null value C# and empty, but not check null Database like DBNull.Value

Related

get all rows from db if parameter added to where clause is null

I have big select with where condition.
WHERE ADB.param1=#param
In Where I send param variable
SqlParameter param1Param = cmd.Parameters.AddWithValue("#param1", param1);
if (param1== null)
{
param1Param.Value = DBNull.Value;
}
This code works the following way.
When query executes it always checks for ADB.param1=param condition and when I send DBNull.Value it gets nothing from database.
But instead of that I want that
if param== null
then it pay no attantion to this condition and get all rows from database. How can I achive that ?
If you want to return all rows where the #param1 parameter is null use...
where (#param1 is null or ADB.param1 = #param1)
If you want to return only those rows where the column value of param is null use...
where ((#param1 is null and ADB.param1 is null) or ADB.param1 = #param1)
Here is one trick which doesn't even require changing your C# code:
WHERE ADB.param1 = COALESCE(#param, ADB.param1)
For non SQL NULL values, the #param must equal the ADB.param1 column. Otherwise, the WHERE clause would always be true, and would return all records.
I assume your query is WHERE ADB.param1=#param1
Try with WHERE (ADB.param1=#param1 OR #param1 IS NULL)

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

DBNull check for ExecuteScalar

The stored procedure for command can return null.Is it correct way to check if the returned value is null or should I also check that obj is null?
object obj = command.ExecuteScalar();
int id = -1;
if (DBNull.Value == obj)
{
id = Convert.ToInt32(obj );
}
You probably want to change your if-statement to
if (obj != null && DBNull.Value != obj) {
...
}
Right now you're trying to convert if obj == DBNull.Value.
If there is no result your query can return null, so in the general case you should check for it. E.g.:
SELECT TOP 1 Col1 FROM TABLE WHERE ...
The above query can return:
null if there are no rows matching the WHERE clause
DBNull.Value if the first matching row has a NULL value in Col1
else a non-null value
If your query is such that you can guarantee there will always be a result, you only need to check for DBNull. E.g.
SELECT MAX(Col1) FROM TABLE WHERE ...
The above query will return DBNull.Value if there are no rows matching the WHERE clause. It never returns null.
And of course there are some cases where you can guarantee a non-null result, in which case you don't need to test for null or DBNull. E.g.
SELECT COUNT(Col1) FROM TABLE WHERE ...
SELECT ISNULL(MAX(Col1),0) FROM TABLE WHERE ...
The above query will always return a non-null value. It never returns null or DBNull.Value.
Use System.DBNull.Value. check this link http://msdn.microsoft.com/en-us/library/system.dbnull%28v=vs.110%29.aspx
Try this :
if(DBNull.Value != obj)
{
....
....
}
Here is difference between Null and DBNull. What is the difference between null and System.DBNull.Value?

Would a NULL value in the DB return a null value in the dataset?

Does a NULL value for a (string) column in the database would return a null value in the dataset record in C# (by default)? Or would it turn into an empty string in the dataset?
In .NET depending on what technologies you use, a NULL value will be returned as null or as DBNull.Value.
When using ADO.NET (System.Data), a database NULL value will generally be returned as DbNull.Value, whereas in (for example) Entity Framework, it will be returned as null.
If you are not doing any other processing, the value will not be returned as an empty string and in no case as the string value "null".
Normally it will return the value DBNull.Value or throw a InvalidCastException. Depending on what you are going to it could turn the DBNull.Value in to a null, but usually when stuff like that happens it really is doing the DBNull.Value check for you and just hiding it. It would not be hard to make a extension method of your own that did it too.
public static string GetStringWithNullCheck(this IDataReader reader, int index)
{
if(reader.IsDBNull(index))
return null;
return reader.GetString(index); //If we called this on a record that is null we get a InvalidCastException.
}
This distinction between null and DBNull.Value is most useful when calling ExecuteScalar(), this allows you to tell the diffrence between "no records returned" and "record returned but the DB contained NULL as the value"
using(var cmd = new SqlCommand(query, connection))
{
var result = cmd.ExecuteScalar();
if(result == null)
{
//0 rows where returned from the query
}
else if(result == DBNull.Value)
{
//Rows where returned but the value in the first column in the first row was NULL
}
else
{
//Result is the value of whatever object was in the first column in the first row
}
}

EF 5.0 inserting null into smallint column

I have a column with SQL type of smallint (EF type of Int16) that I want to insert a null value into but when I use the below code I get the error that null can not be converted to short. How can I get this one line if statment to allow me to insert a null?
CollectionID = (ddlCollection.SelectedValue == "None") ? null : Convert.ToInt16(ddlCollection.SelectedValue)
Working code is to do a nullablecnvert like:
CollectionID = (ddlCollection.SelectedValue == "None") ? (Nullable<Int16>)null : Convert.ToInt16(ddlCollection.SelectedValue)
c# has a values for null in database:
DBNull.Value
The first problem is that your Entity Framework property CollectionID must be marked as Nullable (if you're using EDMX) or declared as short? or Nullable<short> if you're using Code First.
Secondly, you need to make sure the database type for that column is also marked as nullable (something like smallint NULL in SQL Server).
EDIT: Ah, I think I see the problem now. Try casting your call to Convert.ToInt16 to Nullable<short>. The ternary operator sees a null on the true side, and type incompatible with the null value on the false side, which is causing your error.
CollectionID = (ddlCollection.SelectedValue == "None")
? (Nullable<short>)null
: (Nullable<short>)Convert.ToInt16(ddlCollection.SelectedValue)
Use it with sqlcommand parameter
if(ddl_collection.selectedvalue!="None")
command.Parameters.AddWithValue("#CollectionID", Convert.ToInt16(ddlcollection.selectedValue));
else
command.Parameters.AddWithValue("#CollectionID", DBNull.Value);

Categories