Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
How we can enter the special character like , "" % ? etc in sql server table using asp.net with C#?
Please Help me
Posted
Updated 15-Feb-11 2:32am
v4

Use parametrized queries:
C#
using (SqlCommand com = new SqlCommand("INSERT INTO MyTable (message) " +
                                       "VALUES (@M)", con))
    {
    com.Parameters.AddWithValue("@M", @"""%$#@?,.;");
    com.ExecuteNonQuery();
    }
 
Share this answer
 
I found this WITH GOOGLE ( search phrase was "t-sql storing special characters"):

To escape special characters in a LIKE expression you prefix them with an escape character. You get to choose which escape char to use with the ESCAPE keyword. (MSDN Ref)

For example this escapes the % symbol, using \ as the escape char:

SQL
select * from table where myfield like '%15\% off%' ESCAPE '\' 


If you don't know what characters will be in your string, and you don't want to treat them as wildcards, you can prefix all wildcard characters with an escape char, eg:

SQL
set @myString = replace(
                replace(
                replace(
                replace(@myString,'\','\\'),
                        '%','\%'),
                        '_','\_'),
                        '[','\[') 


(Note that you have to escape your escape char too). Then you can use something like this:

SQL
select * from table where myfield like '%' + @myString + '%' ESCAPE '\'


Also remember to allocate more space for your @myString variable as it will become longer with the string replacement.
 
Share this answer
 
This [^]might help you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900