Bob Schneider
asked on
Creating a SQL Query Based on Filters Provided
I want to craft a sql lookup utility on a classic asp website that has one required field and several optional fields. How do i write a query that will look for the required field and then only the optional fields where a search filter has been supplied. The required filter is LastName and the optional filters are FirstName, Gender, City, State, and Email. Here is the query I have if only the LastName is provided:
Thank you very much!
sql = "SELECT p.LastName, p.FirstName, ir.RaceID, ir.ChipTime, ir.ElpsdTime, ir.ChipStart FROM IndResults ir "
sql = sql & "INNER JOIN Participant p ON ir.ParticipantID = p.ParticipantID WHERE p.LastName = '" & sLastName & "'"
Thank you very much!
you can conditionally add the optional parameters:
if sFirstName <> "" then
sql = sql & " AND p.FirstName = '" & sFirstName & "'"
end if
You should NEVER use string contatenation for dynamic SQL. Huge SQL Injection issue.
What if I enter this into the last name field: bob' or 'q'='q
What if I enter this into the last name field: bob' or 'q'='q
agreed, I've preached this a lot to Bob (and others) in the past, but it's up to each developer how valuable security is to them
ASKER
Awesome! Thank you both!!
ASKER
Oops. My bad. So back to the drawing board. Suggestions?
stored procedures and PQ's, like I suggested, are the most secure
>>Suggestions?
Oracle has bind variables. Not sure about the SQL Server equivalent.
Oracle has bind variables. Not sure about the SQL Server equivalent.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
>>ISNULL(p.FirstName,' ') Is Not Null
I'm not a SQL Server Expert so I have to ask: Will that allow index use if there was an index on FirstName?
In Oracle functions on an indexed column will disallow the use of the index.
I'm not a SQL Server Expert so I have to ask: Will that allow index use if there was an index on FirstName?
In Oracle functions on an indexed column will disallow the use of the index.
Surely the great minds at SQL Server development have thought of this situation and provided a way to handle optional criteria in a non-dynamic T-SQL query.... or are we forced to build everything dynamically when optional filters are involved?
This topic is also discussed at:
https://stackoverflow.com/ questions/ 1705634/pr oper-way-t o-handle-o ptional-wh ere-clause -filters-i n-sql
https://stackoverflow.com/
ASKER
Thank you everyone! I guess I'll put together a stored procedure. Not sure of my chances of success with something this complex but might as well give it a shot.
I use following way of applying filters:
where 1 = 1
and p.LastName = isnull(@LastName, p.LastName) -- use this form when column is not null
and 1 = case when @FirstName is null then 1 else case when @FirstName = p.FirstName then 1 else 0 end end -- use this form when column is nullable.
Open in new window