Oracle SQL Where String Constraint Issue [duplicate] - sql

This question already has answers here:
How to avoid variable substitution in Oracle SQL Developer
(5 answers)
Closed 3 months ago.
I am trying to query a certain row by name in my sql database and it has an ampersand. I tried to set an escape character and then escape the ampersand, but for some reason this isn't working and I'm uncertain as to what exactly my problem is.
Set escape '\'
select * from V1144engine.T_nodes where node_id in(
select node2_id from V1144engine.T_edges where node1_id in(
select node2_id from V1144engine.T_edges where node1_id in(
select node2_id from V1144engine.T_edges where node1_id =
(select node_id from V1144engine.T_nodes where node_name = 'Geometric Vectors \& Matrices')))
and edge_type_id = 1)
and node_type_id = 1
and node_id in (
select node2_id from V1144engine.T_edges where node1_id =
(select node_id from V1144engine.T_nodes where node_name = 'Algebra II')
and edge_type_id = 2);

Instead of
node_name = 'Geometric Vectors \& Matrices'
use
node_name = 'Geometric Vectors ' || chr(38) || ' Matrices'
38 is the ascii code for ampersand, and in this form it will be interpreted as a string, nothing else. I tried it and it worked.
Another way could be using LIKE and an underline instead the '&' character:
node_name LIKE 'Geometric Vectors _ Matrices'
The chance that you'll find some other record too, which is different in only this one character, is quite low.

Escape is set to \ by default, so you don't need to set it; but if you do, don't wrap it in quotes.
Ampersand is the SQL*Plus substitution variable marker; but you can change it, or more usefully in your case turn it off completely, with:
set define off
Then you don't need to bother escaping the value at all.

You can use
set define off
Using this it won't prompt for the input

straight from oracle sql fundamentals book
SET DEFINE OFF
select 'Coda & Sid' from dual;
SET DEFINE ON
how would one escape it without setting define.

In order to escape & you can try following ways:-
set scan off
set define off
set escape on
then replace & by\&
replace & by &&
One of them should work at least.
additionally if you are using PL/SQL developer then there is & icon in the bottom of SQL window please go there and disable it. Note in the older version this option is not present.
Also make sure set define off is written at the very beginning of the script.

set escape on
... node_name = 'Geometric Vectors \& Matrices' ...
or alternatively:
set define off
... node_name = 'Geometric Vectors & Matrices' ...
The first allows you to use the backslash to escape the &.
The second turns off & "globally" (no need to add a backslash anywhere). You can turn it on again by set define on and from that line on the ampersands will get their special meaning back, so you can turn it off for some parts of the script and not for others.

This works as well:
select * from mde_product where cfn = 'A3D"&"R01'
you define & as literal by enclosing is with double qoutes "&" in the string.

REPLACE(<your xml column>,'&',chr(38)||'amp;')

I wrote a regex to help find and replace "&" within an INSERT, I hope that this helps someone.
The trick was to make sure that the "&" was with other text.
Find “(\'[^\']*(?=\&))(\&)([^\']*\')”
Replace “$1' || chr(38) || '$3”

--SUBSTITUTION VARIABLES
-- these variables are used to store values TEMPorarily.
-- The values can be stored temporarily through
-- Single Ampersand (&)
-- Double Ampersand(&&)
-- The single ampersand substitution variable applies for each instance when the
--SQL statement is created or executed.
-- The double ampersand substitution variable is applied for all instances until
--that SQL statement is existing.
INSERT INTO Student (Stud_id, First_Name, Last_Name, Dob, Fees, Gender)
VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &fees, '&Gender');
--Using double ampersand substitution variable
INSERT INTO Student (Stud_id,First_Name, Last_Name,Dob,Fees,Gender)
VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &&fees,'&gender');

I know it sucks. None of the above things were really working, but I found a work around. Please be extra careful to use spaces between the apostrophes [ ' ], otherwise it will get escaped.
SELECT 'Hello ' '&' ' World';
Hello & World
You're welcome ;)

Related

Remove template text on regexp_replace in Oracle's SQL

I am trying to remove template text like &#x; or &#xx; or &#xxx; from long string
Note: x / xx / xxx - is number, The length of the number is unknown, The cell type is CLOB
for example:
SELECT 'H'ello wor±ld' FROM dual
A desirable result:
Hello world
I know that regexp_replace should be used, But how do you use this function to remove this text?
You can use
SELECT REGEXP_REPLACE(col,'&&#\d+;')
FROM t
where
& is put twice to provide escaping for the substitution character
\d represents digits and the following + provides the multiple occurrences of them
ending the pattern with ;
or just use a single ampersand ('&#\d+;') for the pattern as in the case of Demo , since an ampersand has a special meaning for Oracle, a usage is a bit problematic.
In case you wanted to remove the entities because you don't know how to replace them by their character values, here is a solution:
UTL_I18N.UNESCAPE_REFERENCE( xmlquery( 'the_double_quoted_original_string' RETURNING content).getStringVal() )
In other words, the original 'H'ello wor±ld' should be passed to XMLQUERY as '"H'ello wor±ld"'.
And the result will be 'H'ello wo±ld'

How to handle/use special characters like percent (%) and ampersand (&) in Oracle SQL queries

I need to include the special character "%" in my LIKE clause in a SQL query, e.g.:
Select * From Some_Table Where Field_Name Like 'bla%bla&2';
How do I write that?
If you want to match Field_Name values that contain 'bla%bla&2', then you need to write this:
set define off
Select * From Some_Table Where Field_Name Like '%bla\%bla&2%' escape '\';
You get to specify which character you want to use to escape a following character (thanks should go to mathguy, not me). You also have to set define off to prevent sqlplus from trying to substitute values in a string.
If, however, you want to match Field_Name values that exactly equal the given string, then you do this instead:
set define off
Select * From Some_Table Where Field_Name = 'bla%bla&2';
If I am not mistakend you escape them with a backslash (\)
Select * From Some_Table Where Field_Name Like 'bla\%bla&2' ESCAPE '\';
Use escape \ to treat is a literal
SELECT *
FROM Some_Table
WHERE Field_Name LIKE 'blah\%'|| 'blah' ||'&'|| '2';
I'll guess that you're using a tool which treats &n, where n is a digit, as a variable marker. If you're using SQL*Plus or SQL Developer you'd need to issue the SQL*Plus command SET DEFINE OFF. Other tools may use other methods to accomplish this.
Best of luck.
I do not think the backslash escape character will work here for the ampersand. Instead, you will want to divide your search into concatenated strings using double pipes. Use single quotes around each piece of literal text. Next, replace the & with chr(38) which is the ampersand. You can see this with:
select chr(38) from dual
You will still want to include the backslash before the % and finish your statement with escape '\'. Notice, I did not quote the chr(38).
select * From Some_Table Where Field_Name Like 'bla\%bla'||chr(38)||'bla' escape '\'

What is this Oracle regexp matching in this production code?

Here's the code that is in production:
dynamic_sql := q'[ with cte as
select user_id,
user_name
from user_table
where regexp_like (bizz_buzz,'^[^Z][^Y6]]' || q'[') AND
user_code not in ('A','E','I')
order by 1]';
Start at the beginning and search bizz_buzz
Match any one character that is NOT Z
Match any two characters that are not Y6
What's the ']' after the 6?
Then what?
I think that StackOverflow's formatting is causing some of the confusion in the answers. Oracle has a syntax for a string literal, q'[...]', which means that the ... portion is to be interpreted exactly as-is; so for instance it can include single quotes without having to escape each one individually.
But the code formatting here doesn't understand that syntax, so it is treating each single-quote as a string delimiter, which makes the result look different that how Oracle really sees it.
The expression is concatenating two such string literals together. (I'm not sure why - it looks like it would be possible to write this as a single string literal with no issues.) As pointed out in another answer/comment, the resulting SQL string is actually:
with cte as
select user_id,
user_name
from user_table
where regexp_like (bizz_buzz,'^[^Z][^Y6]') AND
user_code not in ('A','E','I')
order by 1
And also as pointed out in another answer, the [^Y6] portion of the regex matches a single character, not two. So this expression should simply match any string whose first character is not 'Z' and whose second character is neither 'Y' nor '6'.
When not in couples ] means... Well... Itself:
^[^Z][^Y6]]/
^ assert position at start of the string
[^Z] match a single character not present in the list below
Z the literal character Z (case sensitive)
[^Y6] match a single character not present in the list below
Y6 a single character in the list Y6 literally (case sensitive)
] matches the character ] literally
Start at the beginning and search bizz_buzz
Match any one character that is NOT Z
Match any two one characters that is not Y or 6
What's the ']' after the 6? it's a ]
I'm afraid I have to post this here as the comment section is inappropriate for the formatting required. After your edit above that shows the entire statement, I ran this to see what the string ends up being:
select q'[ with cte as
select user_id,
user_name
from user_table
where regexp_like (bizz_buzz,'^[^Z][^Y6]]' || q'[') AND
user_code not in ('A','E','I')
order by 1]' txt
from dual;
It ended up yielding this:
with cte as
select user_id,
user_name
from user_table
where regexp_like (bizz_buzz,'^[^Z][^Y6]') AND
user_code not in ('A','E','I')
order by 1
It is apparent now that the closing bracket and quote at the end of the regex belong to the first alternate quote string and not to the regex. This is concatenating 2 alternate quoted strings which is a tad confusing as it sure looked like part of the regex. If anything you are learning the importance of comments for the poor person behind you! Please comment this accordingly when you are done figuring this out. Even include a link to this post.

insert string with " ' " to oracle

Hey I'm using oracle DB with Iron Python and I'm having trouble with strings that contains the char " ' " like in Mc'donalds. (I know it is looking for the closing ' )
The string is accepted from the user input and I want to add it to my DB as it is, meaning without omitting or changing any character.
How can I do it?
Try using the "q" (quote) function:
INSERT INTO restaurantTable (name)
VALUES (q'[O'Reilly and Conway's Irish Pub]');
You can also double-up the single apostrophes (O''Reilly and Conway''s Irish Pub). But in your case you'd have to parse them out, so either using the quote function or query parameters would work the best.
For more information: Q-quote operator introduced in Oracle 10g
Taken from PL/SQL, how to escape single quote in a string?
You can do it either using Q quoting like
q'[insert into MY_TBL (Col) values('ER0002')]';
OR you can use two quotes to denote a single quote
'insert into MY_TBL (Col) values(''ER0002'')';

How to enter special characters like "&" in oracle database? [duplicate]

This question already has answers here:
How do I ignore ampersands in a SQL script running from SQL Plus?
(7 answers)
Closed 5 years ago.
I want to insert special character & in my insert statement. My insert is:
INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 & Oracle_14');
If I try to run this query I am getting a popup and it asks me to enter value for Oracle_14.
How can I enter special characters like & in the insert statement for oracle db?
If you are in SQL*Plus or SQL Developer, you want to run
SQL> set define off;
before executing the SQL statement. That turns off the checking for substitution variables.
SET directives like this are instructions for the client tool (SQL*Plus or SQL Developer). They have session scope, so you would have to issue the directive every time you connect (you can put the directive in your client machine's glogin.sql if you want to change the default to have DEFINE set to OFF). There is no risk that you would impact any other user or session in the database.
Try 'Java_22 '||'&'||' Oracle_14'
Justin's answer is the way to go, but also as an FYI you can use the chr() function with the ascii value of the character you want to insert. For this example it would be:
INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 '||chr(38)||' Oracle_14');
you can simply escape & by following a dot. try this:
INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 &. Oracle_14');
To Insert values which has got '&' in it. Use the folloiwng code.
Set define off;
Begin
INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 & Oracle_14');
End ;
And Press F5 from Oracle or Toad Editors.
There are 3 ways to do so :
1) Simply do SET DEFINE OFF; and then execute the insert stmt.
2) Simply by concatenating reserved word within single quotes and concatenating it.
E.g. Select 'Java_22 ' || '& '|| ':' || ' Oracle_14' from dual --(:) is an optional.
3) By using CHR function along with concatenation.
E.g. Select 'Java_22 ' || chr(38)||' Oracle_14' from dual
Hope this help !!!
We can use another way as well
for example to insert the value with special characters 'Java_22 & Oracle_14' into db we can use the following format..
'Java_22 '||'&'||' Oracle_14'
Though it consider as 3 different tokens we dont have any option as the handling of escape sequence provided in the oracle documentation is incorrect.
If an escape character is to be added at the beginning or the end like "JAVA", then use:
INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', ''||chr(34)||'JAVA'||chr(34)||'');
For special character set, you need to check UNICODE Charts. After choose your character, you can use sql statement below,
SELECT COMPOSE('do' || UNISTR('\0304' || 'TTTT')) FROM dual;
--
dōTTTT
Also you can use concat like this :D
Insert into Table Value(CONCAT('JAVA ',CONCAT('& ', 'Oracle'));
strAdd=strAdd.replace("&","'||'&'||'");
In my case I need to insert a row with text 'Please dial *001 for help'.
In this case the special character is an asterisk.
By using direct insert using sqlPlus it failed with error "SP2-0734: unknown command beginning ... "
I tryed set escape without success.
To achieve, I created a file insert.sql on filesystem with
insert into testtable (testtext) value ('Please dial *001 for help');
Then from sqlPlus I executed
#insert.sql
And row was inserted.
You can either use the backslash character to escape a single character or symbol
'Java_22 \& Oracle_14'
or braces to escape a string of characters or symbols
'{Java_22 & Oracle_14}'