求最佳的代码

牧牛人软件 2003-09-13 07:36:49
Sql="select * from tab where amount=:Variable0 and date between :Variable1 and :Variable2 and (account not like :Variable3 or code > :Variable4)";
我想用型如上列的SQL作查询,查询的界面如下:

Amount____________ Date1__________ Date2__________

Account___________ Code______

当用户输入Amount、Date、Account、Code的值后,我把这些常量分别填入:Variable[n]中,然后访问数据库。

【问题】如果用户在某个FIELD没有输入(既为空)就在WHERE中取消查询条件。
例如:
1。Code为空 Where子句就改成:where amount=:Variable0 and date between :Variable1 and :Variable2 and (account not like :Variable3)";

2。Amount为空 Where子句就改成where date between :Variable1 and :Variable2 and (account not like :Variable3 or code > :Variable4)";

3。Date1&Date2为空 Where子句就改成where amount=:Variable0 and (account not like :Variable3 or code > :Variable4)";

4。Account为空 Where子句就改成where amount=:Variable0 and date between :Variable1 and :Variable2 and (code > :Variable4)";
.................
如此等等。
【要求】要考虑各种情况,取消前后相关的关系符,写出最佳的代码。


...全文
46 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
deathsky 2003-10-17
  • 打赏
  • 举报
回复
mark
nuaacims 2003-09-17
  • 打赏
  • 举报
回复
顶...想看好办法
牧牛人软件 2003-09-14
  • 打赏
  • 举报
回复
warton(哈利路亞):
我的SQL等信息(包括查询界面)是事先定制好的,保存在数据库中,这是先决条件。
xrfei 2003-09-13
  • 打赏
  • 举报
回复
可以用:
sql = "select * from tab where 1=1"
然后在后面任意添加and子句。
zihan 2003-09-13
  • 打赏
  • 举报
回复
sql = "select * from tab "
if(Amount != "")
sql = sql + "where amount =: Variable0 and "
else
sql = sql + "where "

if(date != "" &&date2 != "")
sql = sql + "date between :Variable1 and :Variable2 and "

if(account != "")
sql = sql + "(account not like :Variable3 "
else if(Code != "")
sql = sql + "("
else
sql = sql + "(1"

if(Account != "" && Code != "")
sql = sql + "or "

if(Code != "")
sql = sql + "code > :Variable4)"
else
sql = sql + ")";

不过还是觉得太复杂了,干脆用一个case算了,还有就是不知道这个会不会有错!
and (1) 我想让这样表示他始终为真!如果不行,还得把最后一个and去掉!
tccsdn 2003-09-13
  • 打赏
  • 举报
回复
呵呵,第一个,可惜我不会
ThinkX 2003-09-13
  • 打赏
  • 举报
回复
其实这是个很常见的问题了,几乎所有的数据库开发中都会遇到,如果都向zihan(子寒)
一样,那么会写很多的代码,而且容易出错,所以肯定有更好的更通用的办法。
等一等,我一会写一个,我想你会满意的。
warton 2003-09-13
  • 打赏
  • 举报
回复
动态生成呀!生成你要的形式不就行了?
牧牛人软件 2003-09-13
  • 打赏
  • 举报
回复
thp(半天云) :这是不难,但我要的是最佳,或者较好的方法。
warton 2003-09-13
  • 打赏
  • 举报
回复
动态生成呀!生成你要的形式不就行了?
牧牛人软件 2003-09-13
  • 打赏
  • 举报
回复
这是一个动态查询,我的SQL等信息是事先定制好的,保存在数据库中。
thp 2003-09-13
  • 打赏
  • 举报
回复
也不是很麻烦嘛
kingcaiyao 2003-09-13
  • 打赏
  • 举报
回复
让sql语句动态来生成不可以吗?
正如楼上xrfei将sql语句设置成"select * from ....;where 1=1 and",然后根据你的查询条件而在后面添加
牧牛人软件 2003-09-13
  • 打赏
  • 举报
回复
不行!SQL是事先定制好的,这是先决条件。后面不能补。

69,336

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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