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?
Related
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)
I'm having trouble with detecting when my value in C# code is null or not, (I'm using LINQ to call stored procedures from SQL SERVER), I mean I have issues when I want to determine did SQL returned something to me after I called SP which expecting one parameter (ArticleID) or acctualy SQL did not return anything ( null - row does not exist ).
In fact, I want to check does any of my articles has some "Sub articles", and I'm passing ArticleID from C# code to stored procedure.
So In case if article is there, I want to do something with it, in case article with passed ArticleID does not exist I want to do something also, so as I said I need to detect does my article with given ArticleID exist in my sql database.
Here is some of my code:
private void btnCheckForArticle(object sender, RoutedEventArgs e)
{
try
{
if (gridArticles.SelectedItems.Count > 0) {
Article a = (Article)gridArticles.SelectedItem;
if (a.ArticleID != null)
{
var existingArticle = DataServices.POS.proc_GetSubArticleByArticleID(a.ArticleID);
if (existingArticle != null)
{
//DO SOMETHING
return;
}
}
}
}
}
My stored procedure :
ALTER PROCEDURE [dbo].[proc_GetSubArticleByArticleID]
(
#ArticleID int
)
AS
BEGIN
Select *
From SubArticles as S
Where S.ArticleID = #ArticleID
END
It's interesting that I do not know how to detect in c# code is my value null or not, because obliviosuly even if there is no row in sql database still I'm not getting null, and because of that code below existingArticle != null will allways execute..
Now I will post what is happening with article which for sure does not have any subarticles, I mean, where result should be null 100%!
ID that I passed to procedure is 2351, so I executed sp which should return value directly on sql and I replaced #ArticleID with 2351 and ofcourse It did not return me any results, but how can I notice that in my C# code..
because existingArticle will never be null cuz somehow it allways has some value and code below my if (existingArticle != null) will allways execute. what I really dont want :/ ...
Thanks guys!
Cheers
Why don't you call FirstOrDefault()
var existingArticle = DataServices.POS.proc_GetSubArticleByArticleID(a.ArticleID).FirstOrDefault();
if (existingArticle != null)
{
//
return;
}
There is a special Datatype for checking null values from a database.
DBNull.Value
In your case:
if (existingArticle != DBNull.Value)
{
//DO SOMETHING
return;
}
First, modify your SP to have after BEGIN:
SET NOCOUNT ON
This is to avoid interference of "xx rows affected" message.
Seccond, dont do SELECT *, instead use
SELECT 1 From SubArticles as S
Where S.ArticleID = #ArticleID
Last, check for System.DBNull.Value instead of NULL, as this is what will be returned from DDBB. This is because in .Net value types as Boolean can't be null
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
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
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
}
}