Question

Issue with apostrophe in query

Asked by: Dezzar82

Hi All,

I have setup a process loop that runs through a record set one by one to do various things.  

Basically, the database imports new data from a spreadsheet daily, then the process loop selects each record, and based on a number of variables, creates windows folders, .txt files, sends an email and then moves the current to another table.

Its the part where a record gets added to an existing table thats creating the problem when the source data includes an apostrophe '

The data being added with the INSERT INTO query is already defined as a string and might be:
strContactName = "John O'Shea"

I cannot substitute the ' for another character, I cannot eliminate it, I must pass it to the table as is becuase it is translated to the persons email address which contains the apostrophe.  Ie: "John.O'Shea@company.com" which is something I also pass but haven't included in the code example below.

There will not always be an apostrophe, so is there a way to change the syntax to deal with the apostrophe that will not affect other records not containing an apostrophe?

An example of the code portion is noted below:

'*** EXAMPLE SNIPET ****
 
'Select the record set
cSQL = " SELECT tbl_DailyDataImport.SystemID, tbl_DailyDataImport.QuoteNumber, tbl_DailyDataImport.CustomerName, tbl_DailyDataImport.Contact "
cSQL = cSQL & " FROM tbl_DailyDataImport "
 
'Process the record set in a loop
With rsImportProcess
        .MoveFirst
        Do Until rsImportProcess.EOF
        
        If .Fields(1) = this, then do that, etc etc etc
        
        'Also take the contact name and do some translation etc etc to end up with
        strContactName = "John O'Shea"
 
        'Then after processing various things, move the record to a new table
CurrentDb.Execute " INSERT INTO tbl_CurrentQuotes (SystemID, QuoteNumber, CustomerName, Contact)" & _
" SELECT '" & .Fields(0) & "','" & .Fields(1) & "','" & Replace(RTrim(.Fields(2)), "/", ".") & "','" & strContactName & "'"

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-11-03 at 15:36:33ID24869343
Tags

query

,

apostrophe

,

access sql

Topics

Lotus Notes

,

SQL Query Syntax

,

Access Coding/Macros

Participating Experts
3
Points
250
Comments
10

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. apostrophe in query
    I am passing a parameter into a query which builds the "where" clause for the query. For example: SELECT * FROM cus WHERE &x INTO CURSOR temp In this example x="cus.name='Joe's Bank'". I get an error due to the apostrophe but can't wrap the apostrophe...
  2. Replace an Apostrophe
    I am sending a sql statement that is doin an insert - the values that are going into the table come from another query and therefore come as: john's - I need to double up the qoutes and can't simply do a john''s or a john\'\'s. Given a string with one apostrophe I need to re...
  3. That pesky apostrophe '
    Here is the line i use to export my query to excel: DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "qryOutputs", pathname & "\" & Me.txtPrefix & "-" & Me.txtpayroll After the export, it adds the apostrophe to every...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: pcelbaPosted on 2009-11-03 at 15:41:52ID: 25735122

You have to double all apostrophs in the text. Replace function is OK for that:

'*** EXAMPLE SNIPET ****
 
'Select the record set
cSQL = " SELECT tbl_DailyDataImport.SystemID, tbl_DailyDataImport.QuoteNumber, tbl_DailyDataImport.CustomerName, tbl_DailyDataImport.Contact "
cSQL = cSQL & " FROM tbl_DailyDataImport "
 
'Process the record set in a loop
With rsImportProcess
        .MoveFirst
        Do Until rsImportProcess.EOF
        
        If .Fields(1) = this, then do that, etc etc etc
        
        'Also take the contact name and do some translation etc etc to end up with
        strContactName = "John O'Shea"
 
        'Then after processing various things, move the record to a new table
CurrentDb.Execute " INSERT INTO tbl_CurrentQuotes (SystemID, QuoteNumber, CustomerName, Contact)" & _
" SELECT '" & .Fields(0) & "','" & .Fields(1) & "','" & Replace(RTrim(.Fields(2)), "/", ".") & "','" & Replace(strContactName, "'", "''") & "'"
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:

Select allOpen in new window

 

by: QlemoPosted on 2009-11-03 at 15:43:52ID: 25735139

Just double each tick contained in a string.
Any reason why you use a INSERT ... SELECT instead of  INSERT ... VALUES ...?

 

by: pcelbaPosted on 2009-11-03 at 15:48:15ID: 25735162

SELECT saves one pair of parenthesis.

 

by: QlemoPosted on 2009-11-03 at 15:51:53ID: 25735189

Hmm, that's REALLY an argument. Matter of taste.

 

by: Dezzar82Posted on 2009-11-03 at 15:53:05ID: 25735197

thanks for the quick suggestion pcelba! I had tried this previously and it didn't work.  I just tried again and the error is still 3075-Syntax Error.

I'll try and elaborate further.  The ContactName is imported as "John O'Shea"

From this I then translate two things:

strContactName = (some code to break our the first name) = "John"

strContactEmail = (some code to translate John O'Shea into John.O'Shea@company.com)

I then refer to these two strings in the INSERT INTO query exactly the same as noted above.  So the replace function added above returns in the error message (John O''Shea) effectively giving the same error.

 

by: Dezzar82Posted on 2009-11-03 at 15:58:37ID: 25735226

Qlemo, by tick, do you mean ' (apostrophe?) ?

I just tried doubling the opening and closing apostrophe and this results in the same syntax error.

And I use select for not real reason only that its the only way I knew how - I'm self taught....so you don't know what you haven't discovered or been told before...

 

by: Dezzar82Posted on 2009-11-03 at 16:10:09ID: 25735285

pcelba, my apologies, your solution does work.

I found that I was also refering to the apostrophe offending field as  .Fields(3) as per my original example as well as a defined string.

I added the replace function to this field reference as well and it works.

Thank you!

 

by: pcelbaPosted on 2009-11-03 at 16:12:43ID: 25735297

Could you please post the whole command created by the expression:

" INSERT INTO tbl_CurrentQuotes (SystemID, QuoteNumber, CustomerName, Contact)" & _
" SELECT '" & .Fields(0) & "','" & .Fields(1) & "','" & Replace(RTrim(.Fields(2)), "/", ".") & "','" & Replace(strContactName, "'", "''") & "'"

You should also check if the strContactName is not null terminated.

 

by: pcelbaPosted on 2009-11-03 at 16:13:41ID: 25735305

OK, if it works already then ignore my last post.

 

by: SimonAdeptPosted on 2009-11-03 at 16:30:15ID: 25735372

Have you tried assigning your SQL statement to a variable first and debug.print it or examine it's value before executing it?
Those dynamic SQL strings are often a source of error for me, at least. I like to check the string with the actual values in. Unexpected values from ".Replace(RTrim(.Fields(2)), "/", ".")" for example might by causing your syntax error. If fields(2) is the contact name it will contain a single quote for "John O'Shea" that will cause the execute to fail.
It might help if you expand the code snippet you posted, showing the "set rsImportProcess = " line and the derivation of contactname.

As the previous respondents have suggested, it is necessary to double all single quotes in string values in  SQL strings.
I use a "sqlEncode(input as string) as string" function in my databases to prepare each text value that could conceivably contain a single quote. It's a one liner as the previous respondents have suggested replace(input,"'"."''").


20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...