Is it possible to create a parameterized SQL statement that will taken an arbitrary number of parameters? I’m trying to allow users to filter a list based on multiple keywords, each separated by a semicolon. So the input would be something like ‘Oakland;City;Planning’ and the WHERE clause would come out something equivalent to the below:
WHERE ProjectName LIKE '%Oakland%' AND ProjectName Like '%City%' AND ProjectName Like '%Planning%'
It’s really easy to create such a list with concatenation, but I don’t want to take that approach because of the SQL injection vulnerabilities. What are my options? Do I create a bunch of parameters and hope that users never try to use more parameters that I’ve defined? Or is there a way to create parameterized SQL on the fly safely?
Performance isn’t much of an issue because the table is only about 900 rows right now, and won’t be growing very quickly, maybe 50 to 100 rows per year.
A basic proof-of-concept… Actual code would be less, but since I don’t know your table/field names, this is the full code, so anyone can verify it works, tweak it, etc.
I decided to mix a few different answers together into one 😛
This assumes you’ll pass in a delimited string list of search keywords (passed in via @SearchString) as a VARCHAR(MAX), which — realistically — you won’t run into a limit on for keyword searches.
Each keyword is broken down from the list and added into a keyword table. You’d probably want to add code to remove out duplicate keywords, but it won’t hurt in my example. Just slightly less effective, since we only need to evaluate once per keyword, ideally.
From there, any keyword that isn’t a part of the project name removes that project from the list…
So searching for ‘Oakland’ gives 4 results but ‘Oakland;City;Planning’ gives only 1 result.
You can also change the delimiter, so instead of a semi-colon, it can use a space. Or whatever floats your boat…
Also, because of the joins and what not instead of Dynamic SQL, it doesn’t run the risk of SQL Injection like you were worried about.