SQL query using a string with an apostrophe

Status
Not open for further replies.

Malyk

Ars Tribunus Angusticlavius
8,558
Subscriptor
Ok, I'm trying to write a query in a stored procedure in SQL Server 2000. Because some of the parts of the query vary based on certain situations I construct a string that contains the query and then use the exec() function to execute the query.

My problem is that the results of the query may return a field with an apostrophe in it. I handle this in other places using the replace() function, but I can't figure out how to replace a ' in the database with a '' in the result. I've gotten rid of the ' completely, but that isn't what I need. Below is the relevant section of code.

code:<HR>
Code:
set @sql = @sql + 'select bk_note_id, bk_note_type_id, rtrim(footnote_reference), '
set @sql = @sql + 'RTRIM(replace(description, char(39), ''''))  '

That replaces the ' with nothing...so what is in the database as "car's" turns into "cars".

What I don't want to do is repeat the query completely for every different situation. How can I do this replace using a string and the exec() function?

Mike
 

Malyk

Ars Tribunus Angusticlavius
8,558
Subscriptor
CA -

Nope...I've tried up to 10 apostrophe's just hoping that it would work. No dice.

Cobalt -

When storing a ' you need to use two of them ''. However, getting them out is a different story. Basically ' is a string delimiter. So in my string the variable @description contains a string. This makes a string '...the market for cars' look like '...the market for car's' which is an unclosed string expression.

Somehow '...the market for car''''s' = '...the market for cars' in SQL Server 2000.

Using two ' works in general strings, but for some reason doesn't work when it is inside a variable.

Mike
 

TheJet

Ars Praefectus
4,598
Subscriptor++
The reason being that in a variable you don't need to worry about the ' escaping nonsense, however, since you are using a variable to build another SQL string and execute that, then you'll need to do things a bit differently. The first step I would try is to do the RTRIM prior to the REPLACE:

code:<HR>
Code:
set @sql = @sql + 'select bk_note_id, bk_note_type_id, rtrim(footnote_reference), '
set @sql = @sql + 'REPLACE(RTRIM(description), CHAR(39), CHAR(39)+CHAR(39))  '

Also, notice that you really want the CHAR function, rather than the CHR function. I'm still a little confused as to why you actually need the replace at all though...

TheJet

EDIT: The reason that the above statement replaces ' with nothing is because you are surrounding the main string with 's. You have to collapse all inner pairs of 's into a single ', therefore your replace is telling it to replace ' with nothing. If you want it to replace ' with something (like a ') then you need to double everything up:

REPLACE(RTRIM(description), '''''''', '''''''''''')

should work...
 

indigo

Well-known member
5,606
These are a couple of scripts that make life easier. They're vbs, though you should be able to convert them easily enough.

code:<HR>
Code:
Public Function FmtOdbcStrOut(StrI)
  Dim StrIn
  Dim StrOut
  Dim i
  StrIn = Trim(StrI & " ")
  StrOut = ""
  If Len(StrIn) > 0 Then
    For i = 1 to Len(StrIn)
      If ((mid(StrIn,i,1) = "'") or _
          (mid(StrIn,i,1) = chr(145)) or _
          (mid(StrIn,i,1) = chr(146))) Then
        StrOut = StrOut & "''"
      Else
        StrOut = StrOut & mid(StrIn,i,1)
      End If
    Next
  End If
  FmtOdbcStrOut = trim(StrOut & " ")
End Function

Wrap your inserts in that one. It'll take care of special Word Document single quotes too.

You can easily expand the function as needed. Just stick it in an include and use it whenever you feel like it. That's how I manage anyways.

code:<HR>
Code:
Public Function FmtInputValue(StrI)
  If trim(StrI & " ") = "" Then
    FmtInputValue = ""
    Exit Function
  End If
  FmtInputValue = Replace(trim(StrI),chr(34),""")
End Function

This one lets you wrap input values for text boxes and the like with double-quotes, and still get single and double quotes to display properly in the box, and in the input.

Basically, these two functions together mean you don't have to compromise on single or double quotes.

I did not write this code. A developer I work with did. All credit goes to him.
 
When I put strings that possibly have ' in them into a text or varchar field in mySQL I do the following:

$parameters{"description"} =~ s|'|''|g;

Replaces all single ' with two single 's.

When I get a string like:

Mary's dog loves chocolate.

I make it into:

Mary''s dog loves chocolate.

And when I get it into a variable (@tastes = $sth->fetchrow_array;):

$tastes[0] = "Mary's dog loves chocolate."

Would be what it is...

This is just for single quotes, but it works for double quotes too. You don't have to worry about the quotes that encapsulate the string, because they really aren't there. Strings don't have " around them unless you make them have " around them. Is that what you're worrying about?
 

Malyk

Ars Tribunus Angusticlavius
8,558
Subscriptor
In SQL Server 2000 you have to close all strings with '. So if I wanted to create a string in a stored procedure I have to do:

@string = 'This is my string'

If I want to have an apostrophe in the string then I have to do:

@string = 'This is a string with an '' in it'

Inserting things into the databas isn't a problem at all...it's getting them out and then constructing a string with the result. You have to replace the ' that is stored in the database with ''. However, the replace() function in WSQL Server 2000 is a little wierd in this case as you think you should be able to do replace(@string,','') but you can't It doesn't work. You have to use the ascii character codes in the replace and it works fine.

Does that make sense?

Mike
 

indigo

Well-known member
5,606
It's not that. Do a response.write of your recordset. You can pull whatever you want back out. If you want an apostraphe, you insert two right next to eachother. Not a double quote. (just so that's clear, I'm sure you already know this)

When you populate your recordset with a query, all the data comes out fine. No special codes or anything. You can prove this to yourself by doing a response.write on a blank line as opposed to a value in a textbox or something.

See? Now suppose this:

code:<HR>
Code:
<P>rsTemp = conn.execute("select * from table")<P>response.write(rsTemp("String"))<P><input type=text length=20 value='<%=rsTemp("String")%>'>

Now suppose the response.write showed you the String field contained:

code:<HR>
Code:
Where is Mary's dog?

You'd get that out of the response.write, but the Textbox would only have "Where is Mary" in it. Because you truncated the "value" option with that apostraphe. So you think to yourself... well, I'll just use value="<%=rsTemp["String")%>" instead.

OK, now you're getting it. There's a problem though. When rsTemp("String") = 'My name is "indigo" on the Ars Forums', the textbox will only show 'My name is '.

So, they just won't be able to use one or the other then... no biggie right? Wrong. What happens when they paste something from a Worddocument into that textbox? funkyness... that's what.

Or what happens when they want to say: I'm 7'8"!

One either the 8"! gets truncated, or the ! gets truncated.

You have to work within the limits of HTML. So you replace funky Word open/close single quotes with a standard apostraphe, and a standard apostraphe with two when going into the db. When going into an HTML form field, you have to replace either single or double quotes with their character code, and use the other to wrap your values. It would be safer to just replace both and not worry about what you wrap with though... I'm not doing that.

Hope this helps.
 

Malyk

Ars Tribunus Angusticlavius
8,558
Subscriptor
Um...

This has nothing to do with ASP and HTML. I'm not really sure where that came from. It's strickly a SQL Server 2000 stored procedure. Strings in SQL Server are a little odd. Double quotes in a string are completely ok. Sql Server doesn't care. It's when you get into using single quotes that you have a problem. If you are creating a string you have to use two single quotes in a row to get a single quote into the string.

The problem comes when you get to using a string that is constructed with varchar variables and a string. The variable comes strate out of a cell in the database and may or may not have an apostrophe. If you do have an apostrophe you have to replace it with two apostrophe's in order to get it into the string. If you don't you get a string that looks like 'I'm Mike' which is actually one and a half strings ('I' and m Mike'). And that is where the problem lies.

Any better?

Mike
 
Status
Not open for further replies.