Remove multiple values from a field with comma delimited values - SQL - sql

I have to make some changes to a specific field (Oracle DB)
I would like to know what is the best way to remove multiple values from a field with comma delimited values (string) ?
Example:
Before: TYP,CRT,REW,PBR,ORT
Remove TYP, CRT and ORT
After: REW,PBR
Is using a nested REPLACE the only option ?

You can use REGEXP_REPLACE:
UPDATE myTable
SET myColumn =
TRIM(TRAILING ',' FROM REGEXP_REPLACE(myColumn, '(TYP|CRT|ORT)(,|$)'))
The regex looks for TYP, CRT, or ORT followed by a comma or the end of the string. If it gets the very last value (for example the ORT in REW,ORT) it will leave a trailing comma. Rather than overcomplicate the regex, this example removes any trailing commas using the TRIM() function.
There's a SQLFiddle here.
Finally, Frank Schmitt's comment above is spot on - a comma-separated list like this in a column often means poor design. If you can split these values into a related details table you'll probably make things a lot easier.

Related

How can I use ' this symbol in SQL [duplicate]

What is the correct SQL syntax to insert a value with an apostrophe in it?
Insert into Person
(First, Last)
Values
'Joe',
'O'Brien'
I keep getting an error as I think the apostrophe after the O is the ending tag for the value.
Escape the apostrophe (i.e. double-up the single quote character) in your SQL:
INSERT INTO Person
(First, Last)
VALUES
('Joe', 'O''Brien')
/\
right here
The same applies to SELECT queries:
SELECT First, Last FROM Person WHERE Last = 'O''Brien'
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. (Two single quote characters, not double-quote instead of a single quote.)
Note: You should only ever worry about this issue when you manually edit data via a raw SQL interface since writing queries outside of development and testing should be a rare occurrence. In code there are techniques and frameworks (depending on your stack) that take care of escaping special characters, SQL injection, etc.
You just have to double up on the single quotes...
insert into Person (First, Last)
values ('Joe', 'O''Brien')
You need to escape the apostrophe. In T-SQL this is with a double apostrophe, so your insert statement becomes:
Insert into Person
(First, Last)
Values
'Joe', 'O''Brien'
Because a single quote is used for indicating the start and end of a string; you need to escape it.
The short answer is to use two single quotes - '' - in order for an SQL database to store the value as '.
Look at using REPLACE to sanitize incoming values:
Oracle REPLACE
SQL Server REPLACE
MySQL REPLACE
PostgreSQL REPLACE
You want to check for '''', and replace them if they exist in the string with '''''' in order to escape the lone single quote.
Single quotes are escaped by doubling them up,
The following SQL illustrates this functionality.
declare #person TABLE (
[First] nvarchar(200),
[Last] nvarchar(200)
)
insert into #person
(First, Last)
values
('Joe', 'O''Brien')
select * from #person
Results
First | Last
===================
Joe | O'Brien
eduffy had a good idea. He just got it backwards in his code example. Either in JavaScript or in SQLite you can replace the apostrophe with the accent symbol.
He (accidentally I am sure) placed the accent symbol as the delimiter for the string instead of replacing the apostrophe in O'Brian. This is in fact a terrifically simple solution for most cases.
The apostrophe character can be inserted by calling the CHAR function with the apostrophe's ASCII table lookup value, 39. The string values can then be concatenated together with a concatenate operator.
Insert into Person
(First, Last)
Values
'Joe',
concat('O',char(39),'Brien')
use double quotation marks around the values.
insert into Person (First, Last) Values("Joe","O'Brien")
Another way of escaping the apostrophe is to write a string literal:
insert into Person (First, Last) values (q'[Joe]', q'[O'Brien]')
This is a better approach, because:
Imagine you have an Excel list with 1000's of names you want to upload to your database. You may simply create a formula to generate 1000's of INSERT statements with your cell contents instead of looking manually for apostrophes.
It works for other escape characters too. For example loading a Regex pattern value, i.e. ^( *)(P|N)?( *)|( *)((<|>)\d\d?)?( *)|( )(((?i)(in|not in)(?-i) ?(('[^']+')(, ?'[^']+'))))?( *)$ into a table.
If it is static text, you can use two single quote instead of one as below:
DEC #text = 'Khabir''s Account'
See after Khabir there are two single quote ('')
If your text is not static and it is passed in Store procedure parameter then
REPLACE(#text, '''', '')
This is how my data as API response looks like, which I want to store in the MYSQL database. It contains Quotes, HTML Code , etc.
Example:-
{
rewardName: "Cabela's eGiftCard $25.00",
shortDescription: '<p>adidas gift cards can be redeemed in over 150 adidas Sport Performance, adidas Originals, or adidas Outlet stores in the US, as well as online at adidas.com.</p>
terms: '<p>adidas Gift Cards may be redeemed for merchandise on adidas.com and in adidas Sport Performance, adidas Originals, and adidas Outlet stores in the United States.'
}
SOLUTION
CREATE TABLE `brand` (
`reward_name` varchar(2048),
`short_description` varchar(2048),
`terms` varchar(2048),
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
While inserting , In followed JSON.stringify()
let brandDetails= {
rewardName: JSON.stringify(obj.rewardName),
shortDescription: JSON.stringify(obj.shortDescription),
term: JSON.stringify(obj.term),
}
Above is the JSON object and below is the SQL Query that insert data into MySQL.
let query = `INSERT INTO brand (reward_name, short_description, terms)
VALUES (${brandDetails.rewardName},
(${brandDetails.shortDescription}, ${brandDetails.terms})`;
Its worked....
Use a backtick (on the ~ key) instead;
`O'Brien`
the solution provided is not working fine, since it ads the string with two single quote in database, the simplest way is to use anti back slash before the apostrophe (single quote).
Insert into Person (First, Last) Values 'Joe', 'O\'Brien'

Get records matching regex in Ms-Sql

I am using query as follows to get any records that begins with any character, has bunch of 0s and ends with number (1 in this case).
where column like '_%[0]1'
But the issue is it's even returning me d0101 etc. which I don't want. I just want d0001, or r0001. Can I use it to exactly match pattern, not partially using like?
Any other options in ms-sql?
SQL-Server does not really do proper regular expressions but you can generate the search clause you want like this:
where column like '_%1' and column not like '_%[^0]%1'
The second condition will exclude all cases where you have a character other than 0 in the middle of the string.
It will allow strings of all possible lengths, provided they start with an arbitrary character, then have any number of 0s and finish with a 1. All other strings will not satisfy the where clause.
create table tst(t varchar(10));
insert into tst values('d0101');
insert into tst values('d0001');
insert into tst values('r0001');
select * from tst where PATINDEX('%00%1', t)>0
or
select * from tst where t like '%00%1'
You use the _ to say that you don't care what char is there (single char) and then use the rest of the string you want:
DECLARE # TABLE (val VARCHAR(100))
INSERT INTO #
VALUES
('d0001'),
('f0001'),
('e0005'),
('e0001')
SELECT *
FROM #
WHERE val LIKE '_0001'
This code only really handles your two simple examples. If it is more complex, add it to your post.

db2 concatenated rows displaying whitespace

I have a column in a DB2 table where the rows of data consist of two strings, string1 and string2. These have a number of whitespace characters in between them, which I'm trying to remove.
When I run the following, I see the expected result, which is string1 string2.
SELECT REPLACE(COLUMN,' ','') FROM Source_Table;
However when I try to insert the cleansed rows into a new table, the data still contains whitespace between string1 and string2.
INSERT INTO Target_Table (Column)
SELECT REPLACE(Column,' ','') FROM Source_Table;
You probably declared your column as CHAR and DB2 is filling unused space in your column with spaces. That's by design.
If you want to avoid this behavior you should declare the column as VARCHAR
Also in your SELECT you should use the TRIM or RTRIM function for removing the withespaces instead of REPLACE()
You can use trim / rtrim like above said you, or strip function

Regex to get data with special characters

I have some data in my table's column upn.
Here is a small sample set of this data.
Pasquale.Rombolà#it.eurw.domain.net
JuanMaria.RomanGonçalves#eurs.domain.net
Santo.Paternò#it.eurw.domain.net
Peter.Browne#UK.EURW.domain.net
François.ESTIN#fr.eurw.domain.net
Frédéric.Huynh#fr.eurw.domain.net
Frédérique.Psaume#fr.eurw.domain.net
Laura.PiñeiroGomez#eurs.domain.net
Maria.AranzabalSaldaña#eurs.domain.net
Alberto.RubioMuñoz#eurs.domain.net
Peter.Brüggemann#UK.EURW.domain.net
Russel.Peters#CA.domain.net
I want to query this table for UPN values where I have some special characters in the UPN. So my query should not return upns such as:
Peter.Browne#UK.EURW.domain.net
and
Russel.Peters#CA.domain.net
But returns everything else with special characters such as [à,ò,ñ,ü ...etc]
I have tried this query but it doesn't work.
Select * from TableName
Where [UPN] like %[a-z,0-9,#,\.,-,A-Z]%
It returns everything including those which don't have any special characters.
Please help.
If I understand correctly, I think you'll just need to add a "^" as the first character inside the square brackets.
At present you're saying you want to return all those UPNs where one or more characters is in the list you give (i.e. the "ordinary" characters). The "^" should reverse that and give you all the UPNs where at least one of the characters is not in the list you give.
Update: After testing locally ... Make sure your collation is "Accent Sensitive" (if necessary add "Latin1_General_CI_AS" or similar after your "like" clause.
I found it only worked if rather than "A-Z", I actually typed out the whole alphabet.
You need to add binary collate clause in it. Chose necessary collation as per your data. For given sample data Latin1_General_BIN works. Here is the link for collation in sql server.
This snippet worked for me on my machine-
create table #t (name varchar(100));
insert into #t values
('Pasquale.Rombolà#it.eurw.domain.net'),
('JuanMaria.RomanGonçalves#eurs.domain.net'),
('Santo.Paternò#it.eurw.domain.net'),
('Peter.Browne#UK.EURW.domain.net'),
('François.ESTIN#fr.eurw.domain.net'),
('Frédéric.Huynh#fr.eurw.domain.net'),
('Frédérique.Psaume#fr.eurw.domain.net'),
('Laura.PiñeiroGomez#eurs.domain.net'),
('Maria.AranzabalSaldaña#eurs.domain.net'),
('Alberto.RubioMuñoz#eurs.domain.net'),
('Peter.Brüggemann#UK.EURW.domain.net'),
('Russel.Peters#CA.domain.net');
select * from #t where name not like '%[^a-zA-Z0-9#.]%' COLLATE Latin1_General_BIN;
Output-
Peter.Browne#UK.EURW.domain.net
Russel.Peters#CA.domain.net

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 '!';