日期:2014-05-19  浏览次数:20558 次

SQL带多个参数查询问题
根据网址传过来的多个参数查询符合条件的数据,例如asdf.aspx?id=笔记本&Cid=华硕&Did=17。如果网址只传了id=笔记本,其它值为空,那写SQL时要一个个判断来写查询语句还有什么方法就能实现“如果为空就自动选择全部,如果不为空则根据传过来的值做查询”?,如果为后者,aspx当中SQL语句怎么写?

------解决方案--------------------
asdf.aspx?id=笔记本&Cid=华硕&Did=17


string strsql = "select * from table where 1=1 ";
if (Request.QueryString[ "id "] != null
strsql += " and id = " + Request.QueryString[ "id "].ToString();
if (Request.QueryString[ "Cid "] != null)
strsql += " and Cid= " + Request.QueryString[ "Cid "].ToString();

...................
记得and前的空格
------解决方案--------------------
if(id.length > 0) sql += " AND Id = " + id;
if(Cid.length > 0) sql += " AND Cid = " + cid;
下面就不写了,记得前面的WHERE里加个 WHERE 1 = 1

------解决方案--------------------
判断是免不了的,用这个方法还是比较简单点的。
string id,Cid;
if (Request.QueryString[ "id "] != null)
id= " id = " + Request.QueryString[ "id "].ToString();
else
id= " 1=1 ";
if (Request.QueryString[ "Cid "] != null)
Cid= " and Cid= " + Request.QueryString[ "Cid "].ToString();
else
Cid= " and 1=1 ";
string strsql = "select * from table where "+id+Cid;
------解决方案--------------------
where 1=1 时,,如果后面语句asdf.aspx?id=空&Cid=空&Did=空 时,SQL语句也能执行..是全部查询. 没有where 1=1 时,,后面全为空就是where 后面没有条件SQL..就会出现SQL语句错误