An example
Let me explain how that happens in a very simple example. Your query is something like:
query = "SELECT * FROM people WHERE lsname like '" & last_name &"' "
As you can see, we filter the table (people) using the lsname and passing a variable called last_name.Now, imagine this:
last_name = "O'Neill"
As you can see the name contains an apostrophe. That means your query will be executed as:
SELECT * FROM people WHERE lsname like 'O'Neill'
causing an unwanted end to the statement after the O, and leaving the rest of the statement suspended.
The solution
To solve the issue, we can use the REPLACE command.
last_name = REPLACE ( last_name, "'", "''")
The above snippet will replace any apostrophe with a double apostrophe. That will make your query like:
SELECT * FROM people WHERE lsname like 'O''Neill'
making your statement correct.Use REPLACE every time you're dealing with query's variables. You can even think of creating a function to be called before passing parameters.
One last thing: remember that the apostrophe can be use to exploit your code, so you really need to deal with it. Always.
Where would you place: last_name = REPLACE ( last_name, "'", "''")
ReplyDeletein your code?
I do not have write access in sql server
After the Where
Delete