Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL to Query text in access with an apostrophe in it

Tags:

sql

ms-access

I am trying to query a name (Daniel O'Neal) in column names tblStudents in an Access database, however Access reports a syntax error with the statement:

Select * from tblStudents where name like 'Daniel O'Neal'

due to the apostrophe in the name.

How do I overcome this?

like image 998
Kevin Avatar asked Jul 20 '11 15:07

Kevin


People also ask

How do you handle apostrophe in SQL Select query?

1 Answer. The single quote or apostrophe is the special character in SQL which specifies the beginning and end of string data i.e. to use it as part of your literal string data you need to escape the special character.

How do I find an apostrophe in a string in SQL?

You want to use a string insteaed. To put an apostrophe in a string literal you use double apostrophes. Show activity on this post. String sql="select lastname from employee where FirstName like '%"+firstName.


3 Answers

You escape ' by doubling it, so:

Select * from tblStudents where name like 'Daniel O''Neal' 

Note that if you're accepting "Daniel O'Neal" from user input, the broken quotation is a serious security issue. You should always sanitize the string or use parametrized queries.

like image 136
Alex K. Avatar answered Oct 23 '22 16:10

Alex K.


When you include a string literal in a query, you can enclose the string in either single or double quotes; Access' database engine will accept either. So double quotes will avoid the problem with a string which contains a single quote.

SELECT * FROM tblStudents WHERE [name] Like "Daniel O'Neal";

If you want to keep the single quotes around your string, you can double up the single quote within it, as mentioned in other answers.

SELECT * FROM tblStudents WHERE [name] Like 'Daniel O''Neal';

Notice the square brackets surrounding name. I used the brackets to lessen the chance of confusing the database engine because name is a reserved word.

It's not clear why you're using the Like comparison in your query. Based on what you've shown, this should work instead.

SELECT * FROM tblStudents WHERE [name] = "Daniel O'Neal";
like image 42
HansUp Avatar answered Oct 23 '22 16:10

HansUp


Escape the apostrophe in O'Neal by writing O''Neal (two apostrophes).

like image 40
murgatroid99 Avatar answered Oct 23 '22 14:10

murgatroid99