Thursday, 19 April 2012

the right way to construct a sql search query from a list of parameters

.....the right way to construct a sql  search query from a list of parameters...
//this is obviously a c# example but the pattern shud hold gud in general for any freakin language out there


public string constructASearchQuery(searchOperator[] theSearchOperators)
        {


            StringBuilder searchQuery = new StringBuilder(@"select somecolumn from" + "theTable");

            
            if (theSearchOperators != null)
            {

                bool firstCriterion = true;
                int index = 0;
                foreach (searchOperator theSearchCriterion in theSearchOperators)
                {

                    if (theSearchCriterion != null && !(string.IsNullOrEmpty(theSearchCriterion.Id)) && !(string.IsNullOrEmpty(theSearchCriterion.Value)) && !(string.IsNullOrEmpty(theSearchCriterion.OperatorExpression)))
                    {
                        if (firstCriterion)
                        {

                            searchQuery.Append(" where " + theSearchCriterion.Id + theSearchCriterion.OperatorExpression + "'" + theSearchCriterion.Value + "'");
                            firstCriterion = false;
                        }
                        else
                        {
                            searchQuery.Append(" and " + theSearchCriterion.Id + theSearchCriterion.OperatorExpression + "'" + theSearchCriterion.Value + "'");

                        }

                        index++;
                    }
                }




                //if (index > 0) //query constructed

            }
                  return searchQuery.ToString();

        }









No comments:

Post a Comment