在企业应用程序开发中经常遇到,查询数据库的时候,查询的where条件可能不止一个,可能没有条件,也有可能至少一个或者多个条件,遇到这种情况,今天看到论坛上有人用C#的 if 语句拼接,这样解决可以是可以,不过显得太过累赘也没有必要,其实,一句固定的 sql 语句句型即可解决:
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->select * from t
where (a = @a or @a is null)
and (b = @b or @b is null)
and (c = @c or @c is null)
-- 如果参数 @a、@b、@c 的某一个值为 null,则等同于无该条件
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/16436858/viewspace-680672/ ,如需转载,请注明出处,否则将追究法律责任。