我需要为高级搜索表单编写一个SQL查询,如下图所示。
我编写了这个部分sql查询,但我无法使其正常工作,因为如果用户选择第二个复选框并离开第一个复选框,它也会出现语法错误。
strSql = "SELECT ArticleID, ArticleTitle, ArticleDesc, ArticlePublishDate FROM art_Articles WHERE ";
strSql += "( ArticleVisible = 1 AND ArticleActive =1 AND LanguageID =" + LangID +" )";
strSql += " AND ";
strSql += " ( ";
if (cbArchiveTitle.Checked)
{ strSql += " ArticleTitle LIKE N'%" + search + "%' "; }
if (cbArchiveDesc.Checked)
{ strSql += " OR ArticleDesc LIKE N'%" + search + "%' "; }
if (cbArchiveSummary.Checked)
{ strSql += " OR ArticleBodyDesc LIKE N'%" + search + "%' "; }
strSql += ")";
如果我设计我的查询类似
SELECT ArticleID, ArticleTitle, ArticleDesc, ArticlePublishDate FROM art_Articles WHERE
( ArticleVisible = 1 AND ArticleActive =1 AND LanguageID =1 ) AND
( ArticleTitle LIKE N'%Jobs%' OR ArticleDesc LIKE N'%%' )
并将空值传递给未选中的字段,然后我选择了所有行。
我很感激在设计此查询以帮助处理图像
中显示的表单方面有任何帮助答案 0 :(得分:3)
您可以为代码添加一些技巧,以解决未选中第一个复选框的问题:
strSql = "SELECT ArticleID, ArticleTitle, ArticleDesc, ArticlePublishDate FROM
art_Articles WHERE ";
strSql += "( ArticleVisible = 1 AND ArticleActive =1 AND LanguageID =" + LangID +" )";
strSql += " AND ";
strSql += " ( 0 = 1 ";
if (cbArchiveTitle.Checked)
{ strSql += " OR ArticleTitle LIKE N'%" + search + "%' "; }
if (cbArchiveDesc.Checked)
{ strSql += " OR ArticleDesc LIKE N'%" + search + "%' "; }
if (cbArchiveSummary.Checked)
{ strSql += " OR ArticleBodyDesc LIKE N'%" + search + "%' "; }
strSql += ")";
但总的来说,以这种方式编写SQL语句并不是一个好方法。您可以考虑使用Linq之类的技术或至少某些查询构建器(如SelectQueryBuilder
)