八神的技巧之六 sql查询条件的组合技巧(1分)

B

bsense

Unregistered / Unconfirmed
GUEST, unregistred user!
我们经常需要编写查询,但是我们怎么能够简单的实现将不同条件进行组合呢?<br>比如有产品表products ,要按照其 product_no,product_name,product_size,分别查询<br>而product_name ,product_size 要按照模糊查询,三个条件可以1,2,3种分别组合。<br>如果没有输入,就不使用该条件,代码如下:<br>var <br>&nbsp; &nbsp;sProduct_no:string;<br>&nbsp; &nbsp;sProduct_name:string;<br>&nbsp; &nbsp;sProduct_size:string;<br>begin<br>&nbsp; &nbsp;//取得条件<br>&nbsp; &nbsp;sProduct_no := trim(edt_productno.text);<br>&nbsp; &nbsp;sProduct_name := trim(edt_productname.text);<br>&nbsp; &nbsp;sProduct_size:= trim(edt_productSize.text);<br>&nbsp;<br>&nbsp; &nbsp;//sql固定部分<br>&nbsp; &nbsp;zQry.close;<br>&nbsp; &nbsp;zQry.sql.clear;<br>&nbsp; &nbsp;zQry.sql.add('select * from products where 1=1');//注意 1=1 <br><br>&nbsp; &nbsp;//根据条件组合<br>&nbsp; &nbsp;if not(sProduct_no = '') then<br>&nbsp; &nbsp; &nbsp;zQry.sql.add(' and product_no=' + quotedstr(product_no));<br><br>&nbsp; &nbsp;if not(sProduct_name = '') then<br>&nbsp; &nbsp; &nbsp;zQry.sql.add(' and product_name like ''%' + product_name + '%''');<br><br>&nbsp; &nbsp;if not(sProduct_size = '') then<br>&nbsp; &nbsp; &nbsp;zQry.sql.add(' and product_size like ''%' + product_no + '%'''); <br>&nbsp; &nbsp; &nbsp;//为什么需要 ''%' 呢,是因为mssql语法 % 是 匹配符号,模糊查询的意思<br><br>&nbsp; &nbsp;//这里还可以加order by <br>&nbsp; &nbsp;zQry.sql.add(' order by product_no');<br><br>&nbsp; &nbsp;zQry.open;<br><br>至此,一个简单的,填写了内容的 就使用该条件 的 and 组合查询 完成。<br><br>其实用户用得最多的就是这种查询方式。
 
不错,学习
 
接受答案了.
 

Similar threads

I
回复
0
查看
564
import
I
I
回复
0
查看
765
import
I
S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
顶部