简体   繁体   中英

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

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) ...

只需在比较之前添加一个is null校验,如果输入参数值为null ,就会短路,例如:

where (@currentBacklog is null or current_backlog >= @currentBacklog)

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM