I have a slight problem in that I am passing several SQL Server Like queries (which I don’t have control over) in my .Net application and I need to escape some of the characters to make them literals for the database.
For example, suppose the field I am trying to query looks something like:
This_is [a] long_text field with [literal] characters in it
And my query looks something like this:
SELECT * FROM [MyTable] where [MyField] Like 'This_% [literal]%'
Now, this should get that data, the challenge is that the _ and [ characters are not seen by SQL Server as the literal characters, so I have to update my query to:
SELECT * FROM [MyTable] where [MyField] Like 'This[_]% [[]literal]%'
And then it works.
So, my question is that I would like to write a VB.Net function that uses RegEx to find the Like part of the statement and then to replace the characters.
Something along the lines of:
Public Function ConvertQuery(strSQL as string)
... Some kind of Regex that searches for the word "Like"
and then takes everytihng between the 2 "'" characters
Then replaces the "_" with "[_]" and "[" with "[[]"
Return ChangedString
End Function
I know I am giving REALLY bad details, I know what i want, I just can’t figure out how to do it with RegEx.
ALSO, if there is a smarter way to do this with SQL Server Like statments, please also let me know!!!
Thanks!!
Seeing that
C#tag, I assume you are OK with an answer in C#.EDIT