If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Data Access, Manipulation & Batch Languages > Delphi, C etc > Quotes in SQL queries

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 02-17-03, 22:18
aljubicic aljubicic is offline
Registered User
 
Join Date: Jan 2003
Location: Australia
Posts: 46
Question Quotes in SQL queries

Hi all,

I have some select and insert queries that have values that contain text with single quotes (i.e "O'Reilly"). How do I get around this problem when I execute this query as it will error. What can I do with the quote so it used by the query??

I am programming this in Visual Basic 6.

Thanks
Anthony
Reply With Quote
  #2 (permalink)  
Old 02-17-03, 22:34
playernovis playernovis is offline
Registered User
 
Join Date: Nov 2002
Location: San Francisco
Posts: 251
strMySQLString = " SELECT * FROM MyTable WHERE MyName = " & chr(34) & "Smith" & Chr(34)

strMySQLString = " SELECT * FROM MyTable WHERE MyName = " & chr(34) & strInputLastName & Chr(34)



jiri
Reply With Quote
  #3 (permalink)  
Old 02-18-03, 03:49
Ad Dieleman Ad Dieleman is offline
Registered User
 
Join Date: Jan 2003
Location: Dordrecht, The Netherlands
Posts: 95
Re: Quotes in SQL queries

Before you build up the SQL string for the query, double the quotes in the name.

Here's a code example for a function to do this, I use it all the time.

'Begin of code sample
Public Function DoubleQuotes(s As String) As String
Dim a As String, b As String, i As Integer

If Len(s) = 0 Then DoubleQuotes = "": Exit Function

a = "": b = ""
For i = 1 To Len(s)
b = Mid(s, i, 1)
If b = "'" Then b = "''"
a = a & b
Next

DoubleQuotes = a
End Function
'End of code sample

A SQL string would then look like:

strSQL = SELECT * FROM People WHERE Name = '" & DoubleQuotes(strName) & "'"
Reply With Quote
  #4 (permalink)  
Old 02-18-03, 11:53
gannet gannet is offline
Registered User
 
Join Date: Oct 2002
Location: Plymouth UK
Posts: 116
Which database server are you using? Am right in that the problem is with strings with a single quote or apostrophe and the error is returned from the database?

If so, in some variants of SQL you need to put 2 single quotes in the query string, thus:

"O''Reilly"

Note this is a ' followed by another ' not a " although it looks like the later.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On