select-from-where(约束条件为空的问题)

lanlang12 2012-07-24 10:06:29
在C#编程中调用如下语句:
public void CheckInformation(int stuID,string stuName ,int stuAge)
{
string str="select * from Sometable where (ID="+stuID+") and (Name ='" + stuName + "') and (Age="+stuAge+")";
using(OracleDataAdapter thisAdapter = new OracleDataAdapter(str, thisConnection))
{
DataSet thisDataSet = new DataSet();
thisAdapter.Fill(thisDataSet, "Sometable");

...//输出数据
}


}
其中ID,Name ,Age的值为函数参数赋值传入,当键入相应的值时,能够正确查询出相应的数据;
请问:ID,Name为空,Age不为空时,如何忽略查询语句中的ID和Name值,而直接查询出相应Age的数据?如何忽略其中某一项或则某几项输入无效的情况下,判断出有效约束条件并查询出数据?
...全文
378 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
lanlang12 2012-07-24
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 的回复:]
个人常用做法还是诸如
id="+stuID+" or id is null

在数据允许的情况还可以先把stuID做处理,若为Null,则赋予'%',否则赋予原值
然后SQL用id like ="+stuID+"
[/Quote]

谢谢你的解答,问题基本解决了,可是"%"只能赋给字符串,如果碰到定义为整形的数据就不好赋值了。
小德 2012-07-24
  • 打赏
  • 举报
回复
个人常用做法还是诸如
id="+stuID+" or id is null

在数据允许的情况还可以先把stuID做处理,若为Null,则赋予'%',否则赋予原值
然后SQL用id like ="+stuID+"
lanlang12 2012-07-24
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
--最简单的解决办法
string str="select * from Sometable where 1=1 "
string strWhere = "";
if (stuID != "")
{
strWhere = strWhere + " and (ID="+stuID+") ";
}
if (stuName != "")
{
strWhere = strWher……
[/Quote]

兄弟的办法的确是最容易的办法,也很好理解,可是当约束条件过多时,难道每一种情况都要写下来?
还是那句话,用最少的代码实现最有效率最复杂的功能!
  • 打赏
  • 举报
回复
这样吧? or "+stuID+" = ''...
  • 打赏
  • 举报
回复
还有一种方法 一个或者多个为空 对sql没任何影响..


select * from Sometable where (ID="+stuID+" or "+stuID+" is null) and (Name ='" + stuName + "' or '" + stuName + "' is null) and (Age="+stuAge+" or "+stuAge+" is null)";
hupeng213 2012-07-24
  • 打赏
  • 举报
回复
--最简单的解决办法
string str="select * from Sometable where 1=1 "
string strWhere = "";
if (stuID != "")
{
strWhere = strWhere + " and (ID="+stuID+") ";
}
if (stuName != "")
{
strWhere = strWhere + " and (Name ='" + stuName + "') ";
}
if (Age != "")
{
strWhere = strWhere + " and (Age="+stuAge+") ";
}
str = str + strWhere;
  • 打赏
  • 举报
回复
string str="select * from Sometable where (ID="+stuID+") and (Name ='" + stuName + "') and (Age="+stuAge+")";
由于你的where条件传入为空时出问题,改为:

string str="select * from Sometable where 1=1";
if(stuID != null && !stuID.trim().equals("")){
str = str+" and ID = "+stuID;
}
if(stuName != null && !stuName.trim().equals("")){
str = str+" and Name = "+stuName;
}
if(stuAge!= null && !stuAge.trim().equals("")){
str = str+" and Age= "+stuAge;
}

17,086

社区成员

发帖
与我相关
我的任务
社区描述
Oracle开发相关技术讨论
社区管理员
  • 开发
  • Lucifer三思而后行
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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