how to use a string that contain ' in SQL "IN" clause - sql

i have a string value like 'Apple's'. i want to use this string in SQL "IN" clause like below query
select * from tbl_fruit where nm_fruit IN(''Apple's'','Orange');
how i can get the above query work correctly ?
Many Thanks,
Awais Afzal.

double the single quotes,
select * from tbl_fruit where nm_fruit IN ('Apple''s', 'Orange')
but if you do it on the application level, make sure you parameterized the query :)

I have found SQL correctly interprets the ASCII single-closed-quote (ALT 0146) as an apostrophe in searches while the "IN" treats it like any other character. Now I can search for 'Matt's Macintosh' using Matt(ASCII character 0146)s Macintosh" without messing up my list or the search.

Related

SQL Query like Condition not working as expected

I have a query in SQL Server and have values like that is enclosed in the quote. I am trying to filter the value which has CC_ somewhere in the string. In the query when I try to filter the values using %CC_%, it is still returning the values though it is not present in the string.
with a as (
Select '#IDESC("Account"),#IDESC("Period"),#IDESC("View"),#IDESC("Scenario"),#IDESC("Version"),#IDESC("Years"),#IDESC("Currency"),#IDESC("Product"),#IDESC("FX View"),#IDESC("Data_Type"),#IDESC("Entity"),#IDESC("Function"),#IDESC("Market"),#IDESC("Business_Unit"),#IDESC("Reporting_Unit")'
as val)
select * from a where val like '%CC_%'
Can experts please help?
To match literal underscore in a SQL Server LIKE expression, you may place it into square brackets:
SELECT * FROM a WHERE val LIKE '%CC[_]%';
Underscore _ in a LIKE expression literally means any single character, and % means zero or more characters.

How to use regex replace in Postgres function?

I have postgres function in which i am appending values in query such that i have,
DECLARE
clause text = '';
after appending i have some thing like,
clause = "and name='john' and age='24' and location ='New York';"
I append above in where clause of the query i already have. While executing query i am getting "and" just after "where" result in error
How to use regex_replace so that i remove the first "and" from clause before appending it to the query ?
Instead of fixing clause after the fact, you could avoid the problem by using
concat_ws (concatenate with separator):
clause = concat_ws(' and ', "name='john'", "age='24'", "location ='New York'")
will make clause equal to
"name='john' and age='24' and location ='New York'"
This can be even simpler. Use right() with a negative offset.
Truncates the first n characters and you don't need to specify the length of the string. Faster, simpler.
Double quotes (") are for identifiers in Postgres (and standard SQL) and incorrect in your example. Enclose string literals in single quotes (') and escape single quotes within - or use dollar quoting:
Insert text with single quotes in PostgreSQL
Since this is a plpgsql assignment, use the proper assignment operator :=. The SQL assignment operator = is tolerated, too, but can lead to ambiguity in corner cases.
Finally, you can assign a variable in plpgsql at declaration time. Assignments in plpgsql are still cheap but more expensive than in other programming languages.
DECLARE
clause text := right($$and name='john' and age='24' ... $$, -5)
All that said, it seems like you are trying to work with dynamic SQL and starting off on the wrong foot here. If those values can change, rather supply them as values with the USING clause of EXECUTE and be wary of SQL injection. Read some of the related questions and answers on the matter:
https://stackoverflow.com/search?q=[plpgsql]+[dynamic-sql]+EXECUTE+USING
You do not need regex:
clause = substr(clause, 5, 10000);
clause = substr(clause, 5, length(clause)- 4); -- version for formalists
concat_ws sounds like the best option, but as a general solution for things like this (or any sort of list with a delimiter) you can use logic like (pseudocode):
delim = '';
while (more appendages)
clause = delim + nextAppendage;
delim = ' AND ';
If you want to do it with regular expression try this:
result = regexp_replace(clause, '^and ', '')

Select query that displays Joined words separately, not using a function

I require a select query that adds a space to the data based on the placement of the capital letters i.e. 'HelpMe' using this query would be displayed as 'Help Me' . Note i cannot use a stored function to do this the it must be done in the query itself. The Data is of variable length and query must be in SQL. Any Help will be appreciated.
Thanks
You need to use user defined function for this until MS give us support for regular expressions. Solution would be something like:
SELECT col1, dbo.RegExReplace(col1, '([A-Z])',' \1') FROM Table
Aldo this would produce leading space that you can remove with TRIM.
Replace regular expresion function:
http://connect.microsoft.com/SQLServer/feedback/details/378520
About dbo.RegexReplace you can read at:
TSQL Replace all non a-z/A-Z characters with an empty string
Assume if you are using Oracle RDBMS, you use the following,
REGEX_REPLACE
SELECT REGEXP_REPLACE('ILikeToWatchCSIMiami',
'([A-Z.])', ' \1')
AS RX_REPLACE
FROM dual
;
Managed to get this output: * SQLFIDDLE
But as you see it doesn't treat well on words such as CSI though.

How to escape square bracket when using LIKE? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
SQL Server LIKE containing bracket characters
I am having a problem with pattern matching.I have created two objects say,with codes
1)[blah1]
2)[blah2] respectively
in the search tab,suppose if i give "[blah" as the pattern,its returning all the strings
i.e., [blah1] and [blah2]
The query is
select *
from table1
where code like N'%[blah%'
I guess the problem is with the condition and special characters. Please do revert if you have as solution. Is there any solution where we can escape the character"[". I tried to change the condition as N'%[[blah%'.But even then its returning all the objects that is in the table.
When you don't close the square bracket, the result is not specified.
However, the story is different when you close the bracket, i.e.
select *
from table1
where code like N'%[blah%]%'
In this case, it becomes a match for (any) + any of ('b','l','a','h','%') + (any). For SQL Server, you can escape characters using the ESCAPE clause.
select * from table1 where code like N'%\[blah%\]%' escape '\'
SQL Fiddle with examples
You can escape a literal bracket character this way:
select *
from table1
where code like N'%[[]blah%'
Source: LIKE (Transact-SQL), under the section "Using Wildcard Characters As Literals."
I guess this is Microsoft's way of being consistent, since they use brackets to delimit table and column identifiers too. But the use of brackets is not standard SQL. For that matter, bracket as a metacharacter in LIKE patterns is not standard SQL either, so it's not necessary to escape it at all in other brands of database.
As per My understanding, the symbol '[', there is no effect in query. like if you query with symbol and without symbol it shows same result.
Either you can skip the unwanted character at UI Level.
select * from table1 where code like '%[blah%'
select * from table1 where code like '%blah%'
Both shows same result.

Escape percentage sign DB2 SQL

I am trying to select data containing four percentage signs in a row. How can I escape the percentage signs so my LIKE condition works?
Thanks
Use #% with the escape character clause:
select *
from tbl
where fld like '%#%%' escape '#'
This will search for all records that contain the "%" character in the fld column.
DB2/z has a slightly different format:
select *
from tbl
where fld like {escape '#'} '%#%%'
Obviously, you'll need to choose your escape character carefully so it won't interfere with the rest of your string but this is relatively easy for static strings. Dynamically built strings will require dynamically built queries so that it doesn't use a character from the string.