+ -
当前位置:首页 → 问答吧 → 求一sql语句或者其他解决方法

求一sql语句或者其他解决方法

时间:2011-12-14

来源:互联网

窗体上有4个检索条件
startTime
endTime
name
sex
已经在窗体上做了check,至少会有一个检索条件有值

假设表名为naTable,相关字段为timeStart, timeEnd, name, sex,前面两个是datetime类型,需要比较大小,后面varchar型。

这句sql语句该怎么写??

为啥我觉得这个语句很难写呢
4个条件
假设其中只有一个条件有值,那就4种情况了
假设其中有2个条件有值,那就是6种情况了
假设3个条件有值,那就是3种情况了
4个都有值,又是一种情况

这么多情况,一条sql语句怎么写啊??

如果是根据条件情况,组装sql语句,那这条件这么多不得组合很多情况吗??

作者: greyrainbow2010   发布时间: 2011-12-14

按条件,追加sql
string sql = "select * from tableA "
string aaa = " where "
if (startTime != null)
{
  sql=sql + aaa + " timeStart > " + startTime ;
  aaa = " and "
}
if (endTime!= null)
{
  sql= sql + aaa + " timeEnd > " + endTime;
  aaa = " and "

}
if (!string.IsNullOrEmpty(name))
{
  sql= sql + aaa +" name like '%" + name +"%'";
  aaa = " and "
}
if (!string.IsNullOrEmpty(sex))
{
  sql= sql + aaa +" sex ='" + sex +"'";
}



类似这种写法 可以吧  
另外,string最好用stringBuild 代替 ,sql对比时间的地方自己改。

作者: accomp   发布时间: 2011-12-14

ls的方法可以,你怎么不考虑下用存储过程做呢,那样的话效率不是更高点吗!

作者: z_f_p   发布时间: 2011-12-14

string sql="select * from table where 1=1";
if(!string.IsNullOrEmpty(startTime)){
  sql+=" and startTime>'"+startTime+"'";
}....

或者参数化
DbHelper db = new DbHelper();
DbCommand comm = db.GetSqlStringCommond("a");
string sql="select * from table where 1=1";
if(!string.IsNullOrEmpty(startTime)){
  sql+=" and startTime>@startTime";
  db.AddInParameter(comm, "startTime", DbType.String, startTime);
}
comm.CommandText=sql;
....

作者: c02645   发布时间: 2011-12-14

查询条件拼接,并不会是你想的多种情况,sql语句可以分两部分:

select 查询结果 where 查询条件

查询结果可以不变,查询条件开始为空,当你打一个勾后,
就将相应的条件加进去,组成用户希望的条件

当然累加的条件前边记得加 'and '

作者: icdbow   发布时间: 2011-12-14

1楼正解

作者: x4h20   发布时间: 2011-12-14

C# code

string conStr="";
if (startTime != null)
{
  conStr + = ("and  timeStart > '" + startTime +"'");
}
if (endTime!= null)
{
  conStr + = ("and timeEnd > '" + endTime+"'");
}
if (!string.IsNullOrEmpty(name))
{
  conStr+ = ("and Name="+name);
}
if (!string.IsNullOrEmpty(sex))
{
  conStr+ = ("and Sex="+sex);
}
string sql = "select * from tableA where 1=1 "+conStr



用Sql存储过程嘛

作者: ooo7880000   发布时间: 2011-12-14

String sql = "select * from naTable where 1=1";

if (startTime != null) {
sql = sql + "and timeStart > startTime" ;
}

if (endTime!= null) {
sql = sql + "and endTime> startTime" ;
}

if (!string.IsNullOrEmpty(name))
{
  sql= sql + "and Name='" + name+"'";
}
if (!string.IsNullOrEmpty(sex))
{
  sql= sql + "and sex ='" + sex +"'";
}

作者: DarlingYiYi   发布时间: 2011-12-14