简体   繁体   English

SQL查询避免空值参数

[英]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 这些是我要传递给某些方法的变量,我需要编写一些sql查询,例如

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 依此类推,但问题是这些参数很少是这些变量的可选手段,其中值为null,所以我不想在查询中包括这些参数,所以我应该如何消除这些null变量,我没有得到我应该如何编写查询解决这个问题

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 这些参数是随机的,什么时候不会为空,因为它们是可选的,所以无法解决,所以我应该如何只使用非null参数来编写查询

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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