I have a site where I need to be able to search for data and have the query ignore all quotes.
Note: I already am stripping out the quotes for the passed in search term
I want to know if there is an easier (or less verbose) method than:
select Name
from tbl_MyTable
where (Replace(Replace(Replace(Replace(Replace(Replace(Name,'“',''),'‘',''),'''',''),'"',''),'’',''),'”','') like 'dont%'
or Replace(Replace(Replace(Replace(Replace(Replace(Name,'“',''),'‘',''),'''',''),'"',''),'’',''),'”','') like '% dont%' );
Right now, my best idea is to create a new column that contains the quote-stripped version (prepended with a space) so that I can just do:
select Name
from tbl_MyTable
where FixedName like '% dont%';
But I would really like to know if this can be accomplished without creating a new column and have it be efficient.
The simplest method to escape single quotes in SQL is to use two single quotes. For example, if you wanted to show the value O'Reilly, you would use two quotes in the middle instead of one. The single quote is the escape character in Oracle, SQL Server, MySQL, and PostgreSQL.
If you need to use the double quote inside the string, you can use the backslash character. Notice how the backslash in the second line is used to escape the double quote characters. And the single quote can be used without a backslash.
REPLACE(item_description, '"', '') will absolutely remove any " from the column.
The apostrophe, or single quote, is a special character in SQL that specifies the beginning and end of string data. This means that to use it as part of your literal string data you need to escape the special character. With a single quote this is typically accomplished by doubling your quote.
Use a fulltext index instead of LIKE.
Create your fulltext index:
http://msdn.microsoft.com/en-us/library/ms187317.aspx
CREATE UNIQUE INDEX ix1 ON tbl_MyTable(YourKey); //unique index required
CREATE FULLTEXT CATALOG ft AS DEFAULT; // ft is your freetext catalog name
CREATE FULLTEXT INDEX ON tbl_MyTable(Name)
KEY INDEX ix1
WITH STOPLIST = SYSTEM; // this is your index and allows you to run the command below
Then use this to run your query:
SELECT Name
FROM tbl_MyTable
WHERE FREETEXT(Name, 'dont');
That's the fastest technique for this kind of thing. You can get even faster if you use third party free-text engines but there's probably no need for that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With