Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Apostrophe Problems. 2

Status
Not open for further replies.

gnt

Technical User
Aug 15, 2002
94
US
Hello-
I am trying to pull data from the database on our server using a SQL Select statement. The criteria is a string value that is input on a user form, and the results populate a list box. Simple enough. Here's a bit of my code:
Code:
Set objConn = CreateObject("ADODB.Connection")
objConn.Open strConnect
strSQL = "SELECT acctno, name, city, country FROM CustomerVendor WHERE Name LIKE '" & strAgent & "%'"
Set objRS = objConn.Execute(strSQL)
Everything works just fine until the user attempts to search for a string that includes an apostrophe. Then , of course, it confuses the SQL statement. Any ideas on how to solve this?
Thanks!
 
strSQL = "SELECT acctno, name, city, country FROM CustomerVendor WHERE Name LIKE """ & strAgent & "%"""


"The Key, The Whole Key, and Nothing But The Key, So Help Me Codd!"
 
That will be fine until the user enters a string with a quotation mark in. For a complete solution you need to examine the string and replace every occurrence of an apostrophe with two apostrophes, something like

Code:
Dim strAgent As String
Dim strAgent2 As String

Do While InStr(strAgent, "'") > 0
    strAgent2 = strAgent2 & Left(strAgent, InStr(strAgent, "'") - 1) & "''"
    strAgent = Mid(strAgent, InStr(strAgent, "'") + 1)
Loop

strAgent2 = strAgent2 & strAgent

and then use strAgent2 in your SQL instead of strAgent.

Enjoy,
Tony
 
Ahhh, yes. Thanks for the foresight!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top