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"
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 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.
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
How to set Default Value as Value of SqlCommand SqlParameter?
SqlCommand is the class contained in System.Data.SqlClient
My Schema does not accept DBNull.Value as value
SqlCommand command = new SqlCommand();
command.Parameters.Add(new SqlParameter("column_1", SqlDbType.VarChar, 1) { Value = DBNull.Value });
As lboshuizen points out, if your "schema" isn't taking null, or the parameter of the stored procedure or query cannot be null, trying to give it a null value will likely fail. In this case, you need to see why you are trying to set it to null if you know it doesn't accept it. I would surmise an empty string as opposed to null would work, or something else that is sensible.
The SqlParameterCollection property Parameters has an AddWithValue method:
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx
You can simply insert null and that will be handled for you:
command.Parameters.AddWithValue("#parameter", null);
If you cannot provide a null, you can provide something like an empty string:
command.Parameters.AddWithvalue("#parameter", "");
You also very rarely need to specify the data type using this mechanism.
If the schema doesn't accept null it indicates that the column is mandatory and requires a sensible value.
Using a default value for a column is a property of the schema.
So either alter the schema to provide a default.
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
Choose a valid (not null) default value in your application code and use it as a value in the parameter.
const string default = "unknown";
...
SqlCommand command = new SqlCommand();
command.Parameters.Add(new SqlParameter("column_1", SqlDbType.VarChar, 1)
{ Value = default });
Note: Changing the schema to accept NULL is considered cheating :-)
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