IBM Computer, Laptops and Servers

Back Homepage Content Directory Resource Guide Blog

How do I deal with an apostrophe (') in a SQL statement?

Easily one of the most frequently-asked questions in ASP and database-related forums. 
 
The apostrophe is an illegal character in T-SQL because it is interpreted as a string delimiter. To allow a ' mark to be inserted into a database, simply double-up all occurences of the ' mark: 
 
<% 
    criteria = Replace(criteria,"'","''") 
%>
 
So to generate SQL queries: 
 
<% 
    mycrit = Replace(mycrit,"'","''") 
    Response.Write("INSERT table VALUES('" & mycrit & "')<p>") 
    Response.Write("SELECT column FROM table WHERE column LIKE '%" & mycrit & "%'<p>") 
%>
 
In JScript, you could use the Replace() method also, however it behaves differently than in VBScript. Each call to .Replace() only affects the *first* instance it comes across. You can use RegExp to remind JScript to replace globally: 
 
<script language=jscript runat=server> 
    var myCrit = "bob's bait and tackle"; 
    var q = /\'/g; // regexp apostrophe, global 
    myCrit = myCrit.replace(q, "''"); 
    Response.Write("INSERT table VALUES('" + myCrit + "')<P>"); 
    Response.Write("SELECT column FROM table WHERE column LIKE '%" + myCrit + "%'<P>"); 
</script>

[ Comment, Edit or Article Submission ]

Share this:

Add To Yahoo MyWeb Add To Google Bookmarks Add To Furl Fav This With Technorati Add To Newsvine Add To Bloglines Add To Ask Add To Windows Live Add To Slashdot Stumble This Digg This Add To Del.icio.us Add To Reddit

More about:

Oct November 2008 Dec
Sun Mon Tue Wed Thu Fri Sat
            1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30            

IBM Computer, Laptops and Servers Blog on Technorati Related Blog of IBM Computer, Laptops and Servers on Sphere
Content Directory
Resource Guide


Newegg Computer Parts Components Digital Store

Website Links
IBM Computer, Laptops and Servers Copyright © 2008 www.ibmfans.com. All rights reserved. Site Map
Homepage | Blog | Advertise | Privacy Policy | Disclaimer | Contact Us | Links