1

I have the following WHERE condition in a SELECT statement:

WHERE ('.' + column_name LIKE @prefix))

And the @prefix parameter is set as follows:

cmd.Parameters.AddWithValue("@prefix", "%[^a-z]" & prefix & "%")

The prefix variable is taken from form input.

The problem I'm having is when the user enters a '%' or '[' or other special character. How can I make sure these are escaped rather than being treated as special characters?

Related: Generally, how do you stop people entering '%' in their input and having this treated as a wildcard?

2

1 Answer 1

2

SQL's LIKE operator provides an optional ESCAPE clause:

match_expression [ NOT ] LIKE pattern [ ESCAPE escape_character ]

You can set the escape character to a single character of your liking, and escape metacharacters with it.

Sign up to request clarification or add additional context in comments.

4 Comments

Can you give me an example of this for my query?
@Andrew You can use Regex.Replace(prefix, "[~%_[\\]]", "!$0") to escape your prefix with the exclamation point !, and then use exclamation point in your escape clause: column_name LIKE @prefix ESCAPE '!'.
Thanks. I have changed to prefix = Regex.Replace(prefix, "[!~%_[\]]", "!$0"). I gather the ! needs to be escaped since it is the escape character. Also, why did you include ~?
@Andrew "why did you include ~?" Because it is next to the ! on the keyboard, so I pressed the wrong key :) It was supposed to be [!%_[\\]].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.