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_y开发者_高级运维ear>=@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"
精彩评论