0

I need to write a SQL Query for Advance search form shown as Image below.

I wrote this partial sql query but i cant make it work correctly as it also get syntax error if user select second check-box and leaves the first check-box.

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 += ")";

Advanced Search Form If i design my query something like this

 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'%%'  ) 

And pass null value to fields which are not selected then i got all the row selected.

I would appreciate any help in designing this query to work for the form as show in the image

1 Answer 1

3

You can add little trick to you code to resolve the issue with not selected first check box:

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 += ")";

But in general it's not good approach to compose SQL statement in this way. You can consider to use either technologies like Linq or at least some query builder like SelectQueryBuilder

Sign up to request clarification or add additional context in comments.

1 Comment

SelectQueryBuilder Seems like an option i also did it by using a little trick if (cbArchiveTitle.Checked) { strSql += " ArticleTitle LIKE N'%" + search + "%' "; } else { strSql += " ArticleTitle NOT LIKE N'%%' "; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.