How do I search for names with apostrophe in SQL Server? - sql

SELECT *
FROM Header
WHERE (userID LIKE [%'%])

Double them to escape;
SELECT *
FROM Header
WHERE userID LIKE '%''%'

SELECT *
FROM Header WHERE (userID LIKE '%''%')

SELECT * FROM Header WHERE userID LIKE '%' + CHAR(39) + '%'

SELECT * FROM TableName WHERE CHARINDEX('''',ColumnName) > 0
When you have column with large amount of nvarchar data and millions of records, general 'LIKE' kind of search using percentage symbol will degrade the performance of the SQL operation.
While CHARINDEX inbuilt TSQL function is much more faster and there won't be any performance loss.
Reference SO post for comparative view.

That's:
SELECT * FROM Header
WHERE (userID LIKE '%''%')

select * from Header where userID like '%''%'
Hope this helps.

First of all my Search query value is from a user's input.
I have tried all the answers on this one and all the results Google have given me, 90% of the answers says put '%''%' and the other 10% says a more complicated answers.
For some reason all of those did not work for me.
How ever I remembered that in MySQL (phpmyadmin) there is this built in search function so I tried it just to see how MySQL handles a search with an apostrophe, turns out MySQL just escaping apostrophe with a backslash LIKE '%\'%'
so why just I replace apostrophe with a \' in every user's query.
This is what I come up with:
if(!empty($user_search)) {
$r_user_search = str_ireplace("'","\'","$user_search");
$find_it = "SELECT * FROM table WHERE column LIKE '%$r_user_search%'";
$results = $pdo->prepare($find_it);
$results->execute();
This solves my problem.
Also please correct me if this is still has security issues.

Brackets are used around identifiers, so your code will look for the field %'% in the Header table. You want to use a string insteaed. To put an apostrophe in a string literal you use double apostrophes.
SELECT *
FROM Header WHERE userID LIKE '%''%'

Compare Names containing apostrophe in DB through Java code
String sql="select lastname from employee where FirstName like '%"+firstName.trim().toLowerCase().replaceAll("'", "''")+"%'"
statement = conn.createStatement();
rs=statement.executeQuery(Sql);
iterate the results.

Related

SQL Searching for results with apostrophes

I am trying to automate a problem at work and have an SQL question. I am getting a list from one of our vendors strips all of the apostrophes out of the info.
So when I search for "oneil" and my database has "o'neil"
select * from db where name = "oneil"
I know how to fix that by hand, but how would I make it work when I don't know where the apostrophe is at?
I hope I explained that right.
You could first strip the apostrophes from the name before doing the comparison:
SELECT *
FROM db
WHERE REPLACE(name, '''', '') = 'oneil';
Demo
Note that in most versions of SQL, a literal apostrophe is represented inside a string literal using two apostrophes doubled-up ''.
For SQL Server, use a temp table with apostrophes replaced:
select *,
derived_name = REPLACE(t.name,'''','')
into #temp
from table t
Then you can do: select * from #temp where derived_name='oneil'
Note that the apostrophe is also the escape character in sql server.

how to retrieve sql column includes special characters and alphabets

How to retrieve a column containing special characters including alphabets in SQL Query. i have a column like this 'abc%def'. i want to retrieve '%' based columns from that table.
Please help me in this regard.
Is abc%def the column name? or column value? Not sure what you are asking but if you mean your column name contains special character then you can escape them which would be different based on specific RDBMS you are using
SQL Server use []
select [abc%def] from tab
MySQL use backquote
select `abc%def` from tab
EDIT:
Try like below to fetch column value containing % character (Checked, it works in Ingres as well)
select * from tab where col like '%%%'
Others suggest that like '%%%' works in Ingres. So this is something special in Ingres. It does not work in other dbms.
In standard SQL you would have to declare an escape character. I think this should work in Ingres, too.
select * from mytable where str like '%!%%' escape '!';

Sql Server Contains

I need to match on a partial string but can't turn full-text indexing on so can't use contains. I've looked at Levenstein's function for determining the distance between two strings but I'm not looking for fuzzy matching but that every character in the column exists in the string.
I.e. If the string being passed is something like AB_SYS_20120430.TXT I want to match on any columns containing AB_SYS. The like predicate isn't getting me there. I really need the equivalent of the .NET contains feature but as mentioned turning on full text indexing isn't an option to be turned on. Thought I would see if there were any other possible work arounds.
Are you looking for the LIKE function?
http://www.w3schools.com/sql/sql_like.asp
... WHERE MyColumn LIKE '%AB_SYS%'
That may not be optimal, but it seems like it answers your question... If you can search from only the left or right side that could further optimize.
That is functionally similar to String.Contains
http://msdn.microsoft.com/en-us/library/dy85x1sa.aspx
EDIT: How will you parse the input text into the "relevant" substring?
EDIT: To search the same LIKE condition but reverse, from your partial column to the complete literal, simply append the wildcard characters:
... WHERE 'AB_SYS_20120430.TXT' LIKE '%' + MyColumn + '%'
EDIT: You have suggested that you can't get it to work. If you add the schema do your question then I can help you further but consider this:
You have a table called MyTable
In that table there is a column called MyColumn
Some rows in that table have the data 'AB_SYS' in MyColumn
Given the parameter 'AB_SYS_20120430.TXT' you want to return all matching rows
CREATE PROCEDURE MyTestProcedure
#pFullNameString nvarchar(4000) = '' -- parameter passed in, like AB_SYS_20120430.TXT
AS
BEGIN
SELECT
*
FROM
MyTable
WHERE
#pFullNameString LIKE '%' + MyTable.[MyColumn] + '%'
END
GO
You could use CHARINDEX
WHERE CHARINDEX(StringToCheckFor, StringToCheckIn) > 0

Use like in T-SQl to search for words separated by an unknown number of spaces

I have this query:
select * from table where column like '%firstword[something]secondword[something]thirdword%'
What do I replace [something] with to match an unknown number of spaces?
Edited to add: % will not work as it matches any character, not just spaces.
Perhaps somewhat optimistically assuming "unknown number" includes zero.
select *
from table where
REPLACE(column_name,' ','') like '%firstwordsecondwordthirdword%'
The following may help: http://blogs.msdn.com/b/sqlclr/archive/2005/06/29/regex.aspx
as it describes using regular expressions in SQL queries in SQL Server 2005
I would definitely suggest cleaning the input data instead, but this example may work when you call it as a function from the SELECT statement. Note that this will potentially be very expensive.
http://www.bigresource.com/MS_SQL-Replacing-multiple-spaces-with-a-single-space-9llmmF81.html

Ways to escape single quotes in SQL 'LIKE' command

What are the various ways to ESCAPE single quotes(') in the SQL LIKE command?
One way is to put two single quotes whenever you have to escape a single quote.
Can you people suggest something?
Databases: SQL Server 2005 and Oracle 10g
You already have the answer. You have to use two single quotes:
select * from table where field like '%''something''%'
Two single quotes is the best solution.
Alternatively, you can use a CHAR(39) to represent a single quote character.
UPDATE Employee SET LastName = 'O' + CHAR(39) + 'Brien'
WHERE ID=1;
The best way is to bind the parameter with ADO or ADO.NET.
Like (example in C# with ADO.NET):
SqlCommand x = new SqlCommand(sqlConnection, #"select * from table where col like '%'+#para1+'%'");
x.parameters.add(new SqlParameter("#para1",sqltype.varchar,100)).value = "this is a' test";
In SQL Server 2005 you escape a single quote (') with a double single quote ('') if you do not want to bind:
select * from table where col like '%this is a'' test%'
If you want to search the value Allen O'Dea following is the query.
SELECT * FROM [TABLE] WHERE [COLUMN] LIKE '%Allen O''Dea%'
This query works perfectly.
There is also the "Q-quote" method:
select * from mytable where text like q'#%Here's some text%#';
This is available since Oracle 10.2.
I used a '#' character as the quote delimiter, but you can use pretty much any character that won't appear in the string (there are a few exceptions, such as the space character).
In a simple example like that above I probably wouldn't do this. I'd just double up the single quotes, but it does come in handy when building large dynamic SQL statements that include lots of string literals.