How to insert a string which contains an "&" - sql

How can I write an insert statement which includes the & character? For example, if I wanted to insert "J&J Construction" into a column in the database.
I'm not sure if it makes a difference, but I'm using Oracle 9i.

I keep on forgetting this and coming back to it again! I think the best answer is a combination of the responses provided so far.
Firstly, & is the variable prefix in sqlplus/sqldeveloper, hence the problem - when it appears, it is expected to be part of a variable name.
SET DEFINE OFF will stop sqlplus interpreting & this way.
But what if you need to use sqlplus variables and literal & characters?
You need SET DEFINE ON to make variables work
And SET ESCAPE ON to escape uses of &.
e.g.
set define on
set escape on
define myvar=/forth
select 'back\\ \& &myvar' as swing from dual;
Produces:
old 1: select 'back\\ \& &myvar' from dual
new 1: select 'back\ & /forth' from dual
SWING
--------------
back\ & /forth
If you want to use a different escape character:
set define on
set escape '#'
define myvar=/forth
select 'back\ #& &myvar' as swing from dual;
When you set a specific escape character, you may see 'SP2-0272: escape character cannot be alphanumeric or whitespace'. This probably means you already have the escape character defined, and things get horribly self-referential. The clean way of avoiding this problem is to set escape off first:
set escape off
set escape '#'

If you are doing it from SQLPLUS use
SET DEFINE OFF
to stop it treading & as a special case

An alternate solution, use concatenation and the chr function:
select 'J' || chr(38) || 'J Construction' from dual;

The correct syntax is
set def off;
insert into tablename values( 'J&J');

There's always the chr() function, which converts an ascii code to string.
ie. something like:
INSERT INTO
table
VALUES (
CONCAT( 'J', CHR(38), 'J' )
)

You can insert such an string as 'J'||'&'||'Construction'.
It works fine.
insert into table_name (col_name) values('J'||'&'||'Construction');

INSERT INTO TEST_TABLE VALUES('Jonhy''s Sport &'||' Fitness')
This query's output : Jonhy's Sport & Fitness

SET SCAN OFF is obsolete
http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a90842/apc.htm

In a program, always use a parameterized query. It avoids SQL Injection attacks as well as any other characters that are special to the SQL parser.

I've found that using either of the following options works:
SET DEF OFF
or
SET SCAN OFF
I don't know enough about databases to know if one is better or "more right" than the other. Also, if there's something better than either of these, please let me know.

SET ESCAPE ON;
INSERT VALUES("J\&J Construction") INTO custnames;
(Untested, don't have an Oracle box at hand and it has been a while)

If you are using sql plus then I think that you need to issue the command
SET SCAN OFF

Stop using SQL/Plus, I highly recommend PL/SQL Developer it's much more than an SQL tool.
p.s. Some people prefer TOAD.

Look, Andrew:
"J&J Construction":
SELECT CONCAT('J', CONCAT(CHR(38), 'J Construction')) FROM DUAL;

Related

REGEXP REPLACE with backslashes in Spark-SQL

I have a string containing \s\ keyword. Now, I want to replace it with NULL.
select string,REGEXP_REPLACE(string,'\\\s\\','') from test
But unable to replace with the above statement in spark sql
input: \s\help
output: help
want to use regexp_replace
To replace one \ in the actual string you need to use \\\\ (4 backslashes) in the pattern of the regexep_replace. Please do look at https://stackoverflow.com/a/4025508/9042433 to understand why 4 backslashes are needed to replace just one backslash
So, the required statement would become like below
select name, regexp_replace(name, '\\\\s\\\\', '') from test
Below screenshot has examples for better understanding

Unable to replace Char(63) by SQL query

I am having some rows in table with some unusual character. When I use ascii() or unicode() for that character, it returns 63. But when I try this -
update MyTable
set MyColumn = replace(MyColumn,char(63),'')
it does not replace. The unusual character still exists after the replace function. Char(63) incidentally looks like a question mark.
For example my string is 'ddd#dd ddd' where # it's my unusual character and
select unicode('#')
return me 63.But this code
declare #str nvarchar(10) = 'ddd#dd ddd'
set #char = char(unicode('#'))
set #str = replace(#str,#char,'')
is working!
Any ideas how to resolve this?
Additional information:
select ascii('�') returns 63, and so does select ascii('?'). Finally select char(63) returns ? and not the diamond-question-mark.
When this character is pasted into Excel or a text editor, it looks like a space, but in an SQL Server Query window (and, apparently, here on StackOverflow as well), it looks like a diamond containing a question mark.
Not only does char(63) look like a '?', it is actually a '?'.
(As a simple test ensure you have numlock on your keyboard on, hold down the alt key andtype '63' into the number pad - you can all sorts of fun this way, try alt-205, then alt-206 and alt-205 again: ═╬═)
Its possible that the '?' you are seeing isn't a char(63) however, and more indicitive of a character that SQL Server doesn't know how to display.
What do you get when you run:
select ascii(substring('[yourstring]',[pos],1));
--or
select unicode(substring('[yourstring]',[pos],1));
Where [yourstring] is your string and [pos] is the position of your char in the string
EDIT
From your comment it seems like it is a question mark. Have you tried:
replace(MyColumn,'?','')
EDIT2
Out of interest, what does the following do for you:
replace(replace(MyColumn,char(146),''),char(63),'')
char(63) is a question mark. It sounds like these "unusual" characters are displayed as a question mark, but are not actually characters with char code 63.
If this is the case, then removing occurrences of char(63) (aka '?') will of course have no effect on these "unusual" characters.
I believe you actually didn't have issues with literally CHAR(63), because that should be just a normal character and you should be able to properly work with it.
What I think happened is that, by mistake, an UTF character (for example, a cyrilic "А") was inserted into the table - and either your:
columns setup,
the SQL code,
or the passed in parameters
were not prepared for that.
In this case, the sign might be visible to you as ?, and its CHAR() function would actually give 63, but you should really use the NCHAR() to figure out the real code of it.
Let me give a specific example, that I had multiple times - issues
with that Cyrilic "А", which looks identical to the Latin one, but has
a unicode of 1040.
If you try to use the non-UTF CHAR function on that 1040 character,
you would get a code 63, which is not true (and is probably just an
info about the first byte of multibyte character).
Actually, run this to make the differences in my example obvious:
SELECT NCHAR(65) AS Latin_A, NCHAR(1040) Cyrilic_A, ASCII(NCHAR(1040)) Latin_A_Code, UNICODE(NCHAR(1040)) Cyrilic_A_Code;
That empty string Which shows us '?' in substring.
Gives us Ascii value as 63.
It's a Zero Width space which gets appended if you copy data from ui and insert into the database.
To replace the data, you can use below query
**set MyColumn = replace(MyColumn,NCHAR(8203),'')**
It's an older question, but I've run into this problem as well. I found the solution somewhere else on internet, but I thought it would be good to share it here as well. Have a good day.
Replace(YourString, nchar(65533) COLLATE Latin1_General_BIN2, '')
This should work as well:
UPDATE TABLE
SET [FieldName] = SUBSTRING([FieldName], 2, LEN([FieldName]))
WHERE ASCII([FieldName]) = 63

SQL LIKE Command trouble searching for '

Hi I am facing a problem with the like command in SQL,
I want to search for special characters within a column .
The special characters are a single quotation mark ' and { and }..
I have tried placing these special characters under [] but still it doesn't work for '
I have also used the except option but that was also of no help..
Waiting for a response soon
When you specify a value which has single quote, you need to double it.
SELECT *
FROM dbo.Northwind
WHERE Summary LIKE 'single''quotes%'
Try using this-
select * from <table> where <column> like '%''%'
SQL Server escaping is a pain because there are various ways to escape characters, each with different meaning and use case.
A single quote is escaped with another single quote: WHERE myfield LIKE '%''%'.
The general solution is to escape the special character like so:
SELECT .... WHERE my_column like '%\'%' ESCAPE '\'

How to escape a string for use with the LIKE operator in SQL Server?

I am looking for something that works in SQL Server similar to the # symbol in c# which causes a string to be taken as it's literal. Eg:
string text = "abcd\\efg";
Output of text = abcd\efg
string text = #"abcd\\efg";
Output of text = abcd\\efg
Note how the # affected the string to take every character as is.
Now I am not sure this is possible but here is my issue and maybe there is a better way to solve this. Consider the following basic query:
SELECT [Name]
FROM [Test]
WHERE [Name] LIKE (#searchText + '%')
My issue is if they put a %, _ or any other of those special characters that can affect my like clause. I want the match to act just like a 'starts with' function. So is there anything I can apply to the #searchText to say take this literally or is there possbibly a better solution that I am not thinking of?
Edit: I do not want the solution to be client side cleaning. I need this stored proc to work without relying on the data being passed in being cleaned.
To search for "%" as a literal not wildcard in a string, it needs escaped as [%].
Now, SQL Server only need 3 characters escaping: % _ [
So, create a scalar udf to wrap this:
REPLACE(REPLACE(REPLACE(#myString, '[', '[[]'), '_', '[_]'), '%', '[%]')
Because of the simplicity (aka: very limited) pattern matching in SQL, nothing more complex is needed...
In TSQL, you can wrap the % and _ characters in brackets like so [%] [_] this tells SQL to treat them as literals.
I have tested and verified this works in SQL Server 7.0, 2000, and 2005.
http://msdn.microsoft.com/en-us/library/aa933232(SQL.80).aspx
Each character to be treated literally should be enclosed in square brackets. A right bracket is taken literally directly so don't enclose that one.
If you parameterize your query you don't need to worry about it.
UPDATE
As recursive stated in the comments, % still needs to be escaped even in parameterized queries, I didn't realize linq to sql was doing it automagically when I tested.
You can use ESCAPE 'x' where x is the character you wish to be the escape character. Linq to SQL does it like this
WHERE [Name] LIKE #searchText ESCAPE '~'
where #searchText = [some text with a~% character%]
or as others have stated it can be escaped with [%]
view the documentation
I'd sanitize the string in the front-end application rather than try and do hokey stuff in SQL to work around this.
From the docs:
Syntax
match_expression [ NOT ] LIKE pattern
[ ESCAPE escape_character ]
Use the ESCAPE option like so:
SELECT [Name]
FROM [Test]
WHERE [Name] LIKE (REPLACE(#searchText, '%', '%%') + '%') ESCAPE '%'
If you don't want to modify the incoming text, you can use the "LEFT" function to create your own "STARTSWITH":
SELECT [Name]
FROM [Test]
WHERE #searchText = LEFT( [Name], LEN( #searchText ) )
(Note that you probably need to do extra work to handle the case of NULLs or empty string.)
EDIT: Removed the incorrect statement about using "LIKE" to search for "%".

How do I ignore ampersands in a SQL script running from SQL Plus?

I have a SQL script that creates a package with a comment containing an ampersand (&). When I run the script from SQL Plus, I am prompted to enter a substitute value for the string starting with &. How do I disable this feature so that SQL Plus ignores the ampersand?
This may work for you:
set define off
Otherwise the ampersand needs to be at the end of a string,
'StackOverflow &' || ' you'
EDIT: I was click-happy when saving... This was referenced from a blog.
If you sometimes use substitution variables you might not want to turn define off. In these cases you could convert the ampersand from its numeric equivalent as in || Chr(38) || or append it as a single character as in || '&' ||.
I resolved with the code below:
set escape on
and put a \ beside & in the left 'value_\&_intert'
Att
You can set the special character, which is looked for upon execution of a script, to another value by means of using the SET DEFINE <1_CHARACTER>
By default, the DEFINE function itself is on, and it is set to &
It can be turned off - as mentioned already - but it can be avoided as well by means of setting it to a different value. Be very aware of what sign you set it to. In the below example, I've chose the # character, but that choice is just an example.
SQL> select '&var_ampersand #var_hash' from dual;
Enter value for var_ampersand: a value
'AVALUE#VAR_HASH'
-----------------
a value #var_hash
SQL> set define #
SQL> r
1* select '&var_ampersand #var_hash' from dual
Enter value for var_hash: another value
'&VAR_AMPERSANDANOTHERVALUE'
----------------------------
&var_ampersand another value
SQL>
set define off <- This is the best solution I found
I also tried...
set define }
I was able to insert several records containing ampersand characters '&' but I cannot use the '}' character into the text
So I decided to use "set define off" and everything works as it should.
According to this nice FAQ there are a couple solutions.
You might also be able to escape the ampersand with the backslash character \ if you can modify the comment.
I had a CASE statement with WHEN column = 'sometext & more text' THEN ....
I replaced it with
WHEN column = 'sometext ' || CHR(38) || ' more text' THEN ...
you could also use
WHEN column LIKE 'sometext _ more text' THEN ...
(_ is the wildcard for a single character)