sql if 查询数据库

qq_41252618 2018-01-05 02:43:06
只有第一个和第二个if时,两个条件任选一个都可以,但是加了第三个if,strSQL语句就变得只能同时查询两个条件不能单独只查一个了,为什么会这样呢?
if( request.getParameter("Lib") != null && request.getParameter("Capacity")=="")
{

strSQL =strSQL + "where SpaceLibrary = '" + strLib + "'";

}
if( request.getParameter("Lib") =="" && request.getParameter("Capacity")!=null)
{

strSQL =strSQL + "where SpaceCap = '" + strCap + "'";

}
if( request.getParameter("Lib")!=null && request.getParameter("Capacity")!=null)
{

strSQL =strSQL + "where SpaceCap = '" + strCap + "' and SpaceLibrary = '" + strLib + "'";

}
...全文
220 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
文盲老顾 2018-01-05
  • 打赏
  • 举报
回复
两种方式 第一种是在原始的strSql里加where,比如 where id>0,然后判断条件,如果符合条件则追加and
strSQL = strSQL + " where id>0"
if( request.getParameter("Lib") != null && request.getParameter("Capacity")=="")
{
	strSQL =strSQL + " and SpaceLibrary = '" + strLib + "'";
}
if( request.getParameter("Lib") =="" && request.getParameter("Capacity")!=null)
{
	strSQL =strSQL + " and SpaceCap = '" + strCap + "'";
}
另一种是从新声明一个字符串用来生成条件,判断完毕后将新字符串附加到strSQL上
string condition = string.Empty;
if( request.getParameter("Lib") != null && request.getParameter("Capacity")=="")
{
	condition = " where SpaceLibrary = '" + strLib + "'";
}
if( request.getParameter("Lib") =="" && request.getParameter("Capacity")!=null)
{
	strSQL = (string.IsNullOrEmpty(condition)?" where":" and") + " SpaceCap = '" + strCap + "'";
}
strSQL = strSQL + condition

87,907

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧