asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

AddCriteria Simplifies SQL Queries
By Edward Myers
Rating: 3.0 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction

    Occasionally one discovers a subroutine that greatly simplifies a complex ASP page, transforming spaghetti-like code into something that is easy to maintain. In this article I share one such function used when I need to produce an SQL query from a number of optional criteria posted by the user.

    Building an SQL string from optionally posted criteria is tricky. You need to check if the user posted a value since only then is the criteria included in the query. Numeric entries are different from character entries and multiple-selection fields require additional processing to produce a valid SQL query. Fields that might contain single quotes need special attention to prevent syntax errors.

    The AddCriteria function (listed later) elegantly encapsulates the logic to build an SQL statement by adding optional criteria only if the user posted data for a field. Here is an example of how one would use it:

    The Code

    SQL="select * from DataTable" 
    SQL=AddCriteria(SQL,"Status","=","Status","Chr") 
    SQL=AddCriteria(SQL,"PCode","=","Code","Num") 
    SQL=AddCriteria(SQL,"Price",">","LowPrice","Num")
    SQL=AddCriteria(SQL,"Price","<","HighPrice","Num")
    SQL=AddCriteria(SQL,"Category","in","Catg","Num")
    SQL=AddCriteria(SQL,"City","in","City","Chr")
    SQL=AddCriteria(SQL,"Name","like","Name","Chr")
    
    The SQL query is started by specifying everything up to the Where clause. Then the AddCriteria function is used to assemble optionally posted values and append it to the SQL expression. The AddCriteria parameters are almost self-explanatory:

    Parameter 1: The SQL expression as constructed thus far.
    Parameter 2: The database field name for this criterion.
    Parameter 3: The SQL comparison operator for this criterion.
    Parameter 4: The form field name of the posted value.
    Parameter 5: The database field's data type: numeric (Num) or character (Chr).

    If one posted the following data to a page containing the code snippet above, the following SQL statement would be generated:

    Posted Data:
    Status=A&HighPrice=5&Catg=101&Catg=203&Name=Edward SQL Produced:
    select * from DataTable where Status = 'A' and Price < 5 and Category in (101,203) and Name like '%Edward%' Here is the source code for the AddCriteria function: Function AddCriteria(SQL,DBField,Comparison,FormFld,DataType) Dim Value,Val,ValArray,ClauseStyle,Connector AddCriteria=SQL Value=Request.QueryString(FormFld) if len(Value)=0 then Exit Function Comparison=trim(Comparison) DataType=trim(DataType) ClauseStyle=ucase(Comparison & ":" & DataType) select case ClauseStyle case "=:CHR" Value="'" & Replace(Value,"'","''") & "'" case "=:NUM", ">:NUM", "<:NUM" if (not isNumeric(Value)) then Value=0 case "IN:CHR" Value=Replace(Value,", ",",") Value=Replace(Value,"'","''") Value="('" & Replace(Value,",","','") & "')" case "IN:NUM" ValArray=split(Value,",") Value="" for each Val in ValArray if isNumeric(Val) then Value=Value & "," & trim(Val) next if len(Value)< 2 then Exit Function Value=Mid(Value,2) '** remove leading comma Value="(" & Value & ")" case "LIKE:CHR" Value="'%" & Replace(Value,"'","''") & "%'" case else Err.Raise 1,"Function AddCriteria",_ ("Missing case for '" & ClauseStyle & "'") end select Connector=" where " '** for first criterion only if 0<instr(1,SQL,"where") then Connector=" and " AddCriteria=SQL & Connector & DBField & Comparison & Value End Function
    What makes this code elegant is how few If...Then logical constructions are needed. I postulate that the number of coding bugs is directly proportional to the number of If clauses employed, particularly ElseIfs. I reduce the number of If statements required in AddCriteria by cleverly combining the comparison operator and the data type so that each case statement closely represents a single type of SQL clause. Also note the use of the Err object to signal when invalid arguments are provided to AddCriteria, rather than defaulting to an empty result which would sometimes be wrong..

    You may need to modify AddCriteria to fit your situation. If you are using a POST rather than a GET method in your form, you'll need to replace Request.QueryString with Request.Form. If you have different query styles, you may need to extend AddCriteria by adding Case statements for other comparison and data-type values.

    About the Author

    Ed Myers is an independent Web developer living in the Dulles Corridor of northern Virginia. He can be reached by email at ed@myersfamily.com or visit his personal Web site at www.myersfamily.com.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Supporting Products/Tools
    Proposion N2N
    Proposion N2N connects Microsoft .NET applications to Lotus Notes and Lotus Domino databases. This ADO.NET managed data provider allows you to perform blindingly fast queries and updates of Notes data from ASP.NET pages, .NET web services, Windows, or Mobile applications. An innovative SQL-like query language leverages the unique features of Notes and makes collaborative software accessible to relational database programmers.
    [Top]
    Other Articles
    Sep 15, 2005 - Building an Image Keyword System
    Unlike text-based file formats image files aren't made up of words, which makes searching for an image file by keyword difficult. Instead of being able to simply open the file to see what it contains, we're stuck looking at the text around it and other metadata to determine the image's meaning. In this article, Ziran Sun shows you how to build a simple database-based image keyword system that allows you to associate keywords with images and use these keywords to make finding images easier.
    [Read This Article]  [Top]
    Apr 7, 2005 - A Step-by-Step Guide To Using MySQL with ASP.NET - Part 2
    In the second part of of his article on using MySQL with ASP.NET, Ziran Sun covers how to add a new MySQL user to the database server, assign the user the appropriate permissions, connect to the database, and build a simple ASP.NET page to perform a query.
    [Read This Article]  [Top]
    Feb 10, 2005 - A Step-by-Step Guide To Using MySQL with ASP.NET - Part 1
    Back in the days of classic ASP, if you were building a database-driven web site, your choice was either to invest a lot of money to get a copy of Microsoft SQL Server (or some other enterprise-ready database) or invest a lot of time finding a way to deal with the performance and scalability limitations of Microsoft Access. Luckily these days there's another viable alternative: MySQL.
    [Read This Article]  [Top]
    Jan 27, 2005 - Moving a Database from SQL Server 7.0 to SQL Server 2000
    Moving or copying a SQL Server database from one machine to another requires a lot of preparation in order to ensure a smooth transfer. In this article, Dina Fleet Berry examines the different methods and highlights the different issues associated with each of them.
    [Read This Article]  [Top]
    Jan 6, 2005 - Debugging a SQL Stored Procedure from inside SQL Server 2000 Query Analyzer
    There are many times when using SQL Server 2000 Query Analyzer to debug SQL statements is a better choice than debugging in Visual Studio .NET. In this article, Dina Fleet Berry explains why and walks you through the debugging process step-by step.
    [Read This Article]  [Top]
    Nov 24, 2004 - Persisting .NET Objects to SQL Server Using SQLXML and Serialization
    As a follow up to his article on retrieving objects from SQL Server using SQLXML and serialization, Gianluca Nuzzo discusses saving objects back to SQL Server using a schema definition file and updategrams.
    [Read This Article]  [Top]
    Sep 14, 2004 - Transaction Processing in ADO.NET 2.0
    One area that stands out when comparing ADO.NET 1.x to ADO.NET 2.0 is transaction processing. Bill Ryan shows just how easy transaction processing has become with the TransactionScope object in ADO.NET 2.0.
    [Read This Article]  [Top]
    Sep 8, 2004 - Custom Object Data Binding with .NET
    Developers often use brute force coding to marshal data between the GUI and application objects. In this article, Luther Stanton explains how to use .NET's out-of-the box data-binding functionality to make this job much easier.
    [Read This Article]  [Top]
    Sep 2, 2004 - Queue MSMQ Messages from SQL Server
    Learn how to create a console application to queue a message in Microsoft Message Queuing (MSMQ) and then use an extended stored procedure to call the console application from a SQL Server trigger.
    [Read This Article]  [Top]
    Aug 30, 2004 - Tuning Up ADO.NET Connection Pooling in ASP.NET Applications
    Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. This article shows how to monitor the connection pool, diagnose a potential problem, and apply the appropriate fix.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers