Sql多条件查询
以前我们做多条件查询,一种是排列结合,另一种是动态拼接SQL
如:我们要有两个条件,一个日期@addDate,一个是@name
第一种写法是
if (@addDate is not null) and (@name <> '')
select * from table where addDate = @addDate and name = @name
else if (@addDate is not null) and (@name ='')
select * from table where addDate = @addDate
else if(@addDate is null) and (@name <> '')
select * from table where and name = @name
else if(@addDate is null) and (@name = '')
select * from table
第二种就是动态组成SQL,通过exec来执行,我就不写,
昨天我想到一种办法
select * from table where (addDate = @addDate or @addDate is null) and (name = @name or @name = '')
结果一调试,成功,
一点想法,有更好方法的,请指教!~
我的方法:
Dim qm As QueryManager
Dim cv1 As ConcreteView
Dim cv2 As ConcreteView
Dim sql As String
Set qm = m_con.createQueryManager
Set cv1 = m_con.createConcreteView
Set cv2 = m_con.createConcreteView
cv1.sql = "SELECT code FROM TDalop WHERE #namefilter# "
cv1.setFilter "namefilter", "name = :name"
cv1.setParam "name", ".!)(@#&09452342'#''"""
cv2.sql = "SELECT * FROM TDalop WHERE #codefilter# and #uidfilter#"
cv2.setFilter "codefilter", "code in {codelist}"
cv2.addView cv1, "codelist"
cv2.addView cv1, "codelist"
cv2.setFilter "uidfilter", "uid = :uid"
cv2.setParam "uid", "0"
oTestResult.AddTrace cv2.getOutputSql
qm.Execute cv2
# re: sql 多条件查询的一种简单的方法 2004-07-16 23:21 progame
凡是查询的参数为空的,直接使用 1=1 代替,这样就避免了数据库中该字段为null的情况
Dim qm As QueryManager
Dim cv1 As ConcreteView
Dim cv2 As ConcreteView
Dim sql As String
Set qm = m_con.createQueryManager
Set cv1 = m_con.createConcreteView
Set cv2 = m_con.createConcreteView
cv1.sql = "SELECT code FROM TDalop WHERE #namefilter# "
cv1.setFilter "namefilter", "name = :name"
cv1.setParam "name", ".!)(@#&09452342'#''"""
cv2.sql = "SELECT * FROM TDalop WHERE #codefilter# and #uidfilter#"
cv2.setFilter "codefilter", "code in {codelist}"
cv2.addView cv1, "codelist"
cv2.addView cv1, "codelist"
cv2.setFilter "uidfilter", "uid = :uid"
cv2.setParam "uid", "0"
oTestResult.AddTrace cv2.getOutputSql
qm.Execute cv2
# re: sql 多条件查询的一种简单的方法 2004-07-16 23:21 progame
凡是查询的参数为空的,直接使用 1=1 代替,这样就避免了数据库中该字段为null的情况