繁体   English   中英

SQL查询避免空值参数

[英]sql query to avoid null value parameter

这些是我要传递给某些方法的变量,我需要编写一些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";

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

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

您可以测试条件中的空值,并改用表中的值。 例:

... where course_id = isnull(@courseId, course_id) ...

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

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

而不是拥有

cmd = "one long string with many clauses, some of which are optional"

尝试

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