目的是动态查询,查询语句先加上WHERE 1=1,然后后面的条件不论是有一个或者多个都可以直接写为AND <condition>.
dim sqlstmt as new StringBuilder
sqlstmt.add("SELECT * FROM Products")
sqlstmt.add(" WHERE 1=1")
''// From now on you don't have to worry if you must
''// append AND or WHERE because you know the WHERE is there
If ProductCategoryID <> 0 then
sqlstmt.AppendFormat(" AND ProductCategoryID = {0}", trim(ProductCategoryID))
end if
If MinimunPrice > 0 then
sqlstmt.AppendFormat(" AND Price >= {0}", trim(MinimunPrice))
end if
本文详细阐述了如何通过动态查询优化SQL语句,采用先设WHERE1=1作为基础查询条件,后续根据具体需求灵活添加AND或WHERE条件,有效提升查询效率并简化代码逻辑。实例展示了在产品类别ID和最小价格筛选条件下的SQL语句实现。

被折叠的 条评论
为什么被折叠?



