首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > oracle >

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

2012-08-09 
select-from-where(约束条件为空的问题)在C#编程中调用如下语句:public void CheckInformation(int stuID,

select-from-where(约束条件为空的问题)
在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的数据?如何忽略其中某一项或则某几项输入无效的情况下,判断出有效约束条件并查询出数据?

[解决办法]
--最简单的解决办法
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;
[解决办法]
还有一种方法 一个或者多个为空 对sql没任何影响..

C# code
select * from Sometable where (ID="+stuID+" or "+stuID+" is null) and (Name ='" + stuName + "' or '" + stuName + "' is null) and (Age="+stuAge+" or "+stuAge+" is null)";
[解决办法]
个人常用做法还是诸如
id="+stuID+" or id is null

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

热点排行
Bad Request.