ExecuteScalar with WHERE clause not matching all rows - c#

I have been researching why my below OleDBCommand ExecuteScalar function is not properly returning the correct data.
query = "SELECT Count(*) FROM NoteTable WHERE SQLMigrationFl <> 'Y'";
command = new OldDbCommand(query, connection);
var remainingNotes = (int)command.ExecuteScalar();
My connection is defined previously, and is successfully used by other queries. My Access database has 99 records in it; however, when I run the above code it only returns 10. When I remove the WHERE statement it returns all 99; however, that will not help when the SQLMigrationFl begins to be populated with a 'Y'. Any thoughts on why the ExecuteScalar function is not returning what I expect it to?
Thanks

If your SQLMigrationFl column can contain NULL values then you'll need to test for that condition, too. WHERE SQLMigrationFl <> 'Y' will not match rows where SQLMigrationFl IS NULL because NULL values are never equal (or unequal) to any other value. That is,
NULL = 'Y' is false, but
NULL <> 'Y' is also false, and even
NULL = NULL is false, which is why we need to use WHERE ... IS NULL to test for NULL values.

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)

Insert null value in bit(Datatype) [duplicate]

I want a value to be set to NULL if nothing is put into the text box in the form I'm submitting. How can I make this happen?
I've tried inserting 'NULL' but this just adds the word NULL into the field.
I'm not sure what code I should provide for this, I'm just writing an UPDATE query.
Don't put NULL inside quotes in your update statement. This should work:
UPDATE table SET field = NULL WHERE something = something
You're probably quoting 'NULL'. NULL is a reserved word in MySQL, and can be inserted/updated without quotes:
INSERT INTO user (name, something_optional) VALUES ("Joe", NULL);
UPDATE user SET something_optional = NULL;
UPDATE MyTable
SET MyField = NULL
WHERE MyField = ''
You should insert null, not the string of 'NULL'.
Use NULL (without the quotes around it).
UPDATE users SET password = NULL where ID = 4
if (($_POST['nullfield'] == 'NULL') || ($_POST['nullfield'] == '')) {
$val = 'NULL';
} else {
$val = "'" . mysql_real_escape_string($_POST['nullfield']) . "'";
}
$sql = "INSERT INTO .... VALUES ($val)";
if you put 'NULL' into your query, then you're just inserting a 4-character string. Without the quotes, NULL is the actual null value.
Assuming the column allows a null setting,
$mycolupdate = null; // no quotes
should do the trick
The answers given here are good but i was still struggling to post NULL and not zero in mysql table.
Finally i noted the problem was in the insert query that i was using
$quantity= "NULL";
$itemname = "TEST";
So far so good.
My insert query was bad.
mysql_query("INSERT INTO products(quantity,itemname)
VALUES ('$quantity','$itemname')");
I corrected query to read.
mysql_query("INSERT INTO products(quantity,itemname)
VALUES ('".$quantity."','$itemname')");
So the $quantity is outside of the main string.
My sql table now accepted to record null quantity instead of 0
The problem you had is most likely because mysql differentiates between null written in capital letters and null written in small case.
So if you used an update statement with null, it would not work. If you set it to NULL, it would work fine.
Thanks.

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

C# Check null in LINQ query and Transaction Scope giving underlying connection failed to open

I have been messing with 2 problems for quite some time and i have tried alot of things but still i am getting the problems. Following is the simplified version of the first problem.
I have a LINQ query in which p.XP and XP is of type double? . When the value of XP is "null" the query return wrong results even though i have a null in the p.XP field in the database.
from p in entity.positions
where p.XP == XP
select p;
I also tried different things suggested by other threads on SO like
from p in entity.positions
where Object.Equals(p.XP , XP)
select p;
This gives me following exception
Unable to cast type System.Nullable to System.Object.
How to resolve this issue ?
Problem 2:
For LINQ i am using TransactionScope to handle transactions. When i execute the queries i get an exception
Underlying connection failed to Open.
and the inner exception is saying something about DTC. I read online that i will have to enable some service on the server. But i donot want to do that. How can i use transcactions without enabling DTC. My code is something like this
public void function1()
{
using(TransactionScope t = new TransactionScope())
{
RunSomeSelectQueries();
RunSomeInsertQueries();
RunSomeUpdate Queries();
t.Complete();
}
}
These are really two problems and should be separated into two questions.
But I do have an answer for the first one. In SQL database NULL is not equal to NULL. This is because NULL is meant to represent and unknown value and it is not possible to declare that an unknown is equal to another unknown.
To clarify:
"SELECT * FROM sometable where 1 = 1" would return all rows, because "1 = 1" is TRUE
"SELECT * FROM sometable where 1 = 0" would return no rows, because "1 = 0" is FALSE
"SELECT * FROM sometable where NULL = NULL" or "SELECT * FROM sometable where 1 = NULL" would return no rows, because "NULL = NULL" or "1 = NULL" is equal to a new "boolean" state called NULL. A query will only return a row if the WHERE clause is TRUE.
To extract the row where XP is NULL, you must expand your where clause to something like this:
from p in entity.positions
where p.XP == XP || (p.XP == null && XP == null)
select p;
In your first problem, you need to check for nulls separately from the comparisons, because nulls are treated separately.
var foo = (from p in entity.positions
where (p.XP == null && XP == null)
|| (p.XP == XP)
select p);

sql query to avoid null value parameter

these are the variables i am passing to some method where i need to write some sql query like
string cmd = #"select *
from students_tbl
where
course_id=#courseId and branch_id=in(+" branchId "+)
and passout_year>=#passoutYear
and current_backlog>=#currentBacklog
and gender=#gender
and eGap<=#eGap
and first_year_percent>=#firstyearPercent
and second_year_percent>=#seconYearPercent
and third_year_percent>=#thirdyearPercent";
and so on but problem is that few of these parameters are optional means for those variable
there value is null so i don't want to include those parameter in query
so how should i eliminate those null variable i am not getting how should i write query to solve this issue
those parameter are random nothing fix when they will be null because hey are optional
so how should i write query by using only not null parameter
Just add an is null check before your comparison, which will short-circuit if the input parameter value is null, e.g.:
where (#currentBacklog is null or current_backlog >= #currentBacklog)
You can test for a null value in the condition, and use the value from the table instead. Example:
... where course_id = isnull(#courseId, course_id) ...
Instead of having
cmd = "one long string with many clauses, some of which are optional"
try
cmd = "first clause, required"
if second param is not null then
cmd = cmd & "second clause, optional"

Categories