簡體   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