SQL to Query text in access with an apostrophe in it

后端 未结 5 993
你的背包
你的背包 2020-12-14 00:33

Please help me with this because I cannot seem to get it right

I am trying to query a name(Daniel O\'Neal) in column names tblStudents in an access database however

相关标签:
5条回答
  • 2020-12-14 01:05

    How about more simply: Select * from tblStudents where [name] = replace(YourName,"'","''")

    0 讨论(0)
  • 2020-12-14 01:12

    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";
    
    0 讨论(0)
  • 2020-12-14 01:17

    ...better is declare the name as varible ,and ask before if thereis a apostrophe in the string:

    e.g.:

    DIM YourName string

    YourName = "Daniel O'Neal"

      If InStr(YourName, "'") Then
          SELECT * FROM tblStudents WHERE [name]  Like """ Your Name """ ;
       else
          SELECT * FROM tblStudents WHERE [name] Like '" Your Name "' ;       
      endif
    
    0 讨论(0)
  • 2020-12-14 01:18

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

    0 讨论(0)
  • 2020-12-14 01:22

    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.

    0 讨论(0)
提交回复
热议问题