We have an application where users can type search terms. For our needs, these can be separated by spaces, so the number of keywords is variable. Depending on each term, we will look for the exact keyword or use LIKE
. We look for one OR the other and we query more than one table.
This question is mainly about how to mitigate SQL injection risk, but if a side-solution for the requirement removes this risk, that will work as well. I'm surely doing something wrong and/or missing something obvious, but cannot figure out what. I already considered:
- using table parameters
- parametrizing the tokens
- trying to remove malicious characters/commands (in vain, of course)
Also already read as usual several blog posts and Q&As. Maybe the solution is one of the above, but then I would appreciate basic guidance about how to implement it concretely. Here is the minimum information to explain what we're trying to achieve:
User input (space separated, except between quotes):
A "B*C D" EF* G
Tokens
A
B*C D
EF*
G
Clauses
= 'A'
LIKE '%B%C D%'
= 'D'
LIKE '%EF%'
Target query (ex. with 2 tables, A
and B
):
SELECT A.* FROM A WHERE A.a = 'A' OR LIKE '%B%C D%' ... (dynamic clauses)
UNION ALL
SELECT B.* FROM B WHERE B.a = 'A' OR LIKE '%B%C D%' ...
Notes
- We're coding in C# and we can do whatever we want in code.
- We're using Dapper.
Question
Is it possible to parametrize this? Else what would be the best strategy to build the query? Should we add functions that return the clauses, or split queries by table in different stored procedures...?