views:

30

answers:

1

I'm writing a query that has to count the number of students enrolled in a course, and the way I'm doing it is like this:

DCount("[student/course table].[Student ID]","[student/course table]","[StartDate] = #" & [Course Start Date] & "# AND Location = '" & tblCourseDetails.Location & "' AND [Course Number] = '" & [Course Number] & "'")

The problem is that Location can contain apostrophes, which throws errors into my results. This seems to screw up a lot of things (like it asks for me to enter a parameter twice). Is there any simple way to get around apostrophes? I was thinking maybe using Replace()=Replace() which would be a pretty simple solution, but if there's any other ways around this I'd like to know.

I'm not too worried about SQL injection. To use this query you'd have pretty much access to the database anyways.

This isn't my whole query, if you think I should post it, tell me.

+3  A: 

You need to add an escape character. For access I believe it is '' for '.

So find and replace ' with '' and you should be good to go.

Edit: That is an extra apostrophe, not a double quotation mark.

Replace(tblCourseDetails.Location, "'", "''")
buckbova
Jeff
Remou
Jeff
@Jeff I'm sorry I'm a bit confused by your last question.
buckbova
It's nothing important, but whenever I run Repalce(Location, "'", "''") within the DCount criteria string, it gives me a syntax error. I believe it's because it's going outside of the string with the first ". But I'm not sure
Jeff
Yes, you can put Replace in DCount, but I cannot think of a reason why you would want to `DCount("*","Example","Data=Replace(Data,""'"",""''"")")`
Remou
It's more for understanding how strings work in SQL I suppose. So " in front of a " (like "") escapes the "? Are most things escaped by doubling themselves?
Jeff
While you can use DCount in SQL inside Access, it is not standard SQL. Double quotes are more VBA than SQL, and doubling is only for quotes, not other special characters.
Remou