How to remove \n from a mysql variable - mysql

I have the following mysql variable.
SET #theSQL = 'CREATE VIEW `Reports` AS
SELECT DISTINCT
id from mytable;'
On inspecting the variable it has the following value,
'CREATE VIEW `Reports` AS\n SELECT DISTINCT\n
Is there a way to remove the \n without having to do it manually?

Use the REPALCE function
REPLACE(#theSQL, '\n', '')

Replace will do the trick. Always replace with a space when you're handling strings containing SQL statements: removing whitespace can trash the statement. On my rig I have to cope with both \r and \n so I use this.
SET #theSQL = REPLACE(REPLACE(#theSQL , '\n', ' '), '\r', ' ');
But, Gordon is right. You can give MySQL's PREPARE a text string containing returns and newlines and it will work just fine.

Related

Multiple string replace in apache drill using REGEXP_REPLACE sql method

I am using drill sql query on json data. But one of my json field seems to have few characters e.g. '\n' & '^' etc which I want to replace on the fly.
Currently, I am calling REGEXP_REPLACE twice as below -
SELECT REGEXP_REPLACE(REGEXP_REPLACE('aaaa\nbbbb^cccc', '\\n', ' '), '\^', ' ') FROM (VALUES(1));
How can I do that using REGEXP_REPLACE method only once?
The below must work -
SELECT REGEXP_REPLACE('aaaa\nbbbb^cccc', '\\n|\^', ' ') FROM (VALUES(1));
But note that in this case, the character you are replacing with, will be same for all. If you have to replace with different characters then you would need to go with your approach only as below -
SELECT REGEXP_REPLACE(REGEXP_REPLACE('aaaa\nbbbb^cccc', '\\n', 'X'), '\^', 'Y') FROM (VALUES(1));

MYSQL : match and remove matched word from string

I have to remove word from string when matched found
let's see
My input string is
'KENOX ROAD'
Table of words from with match perform
STREET
DRIVE
ROAD
4. DRIVE WAY
Out string should be :
KENOX
I am using vb.net for this windows form application.I am getting input string from textbox and on a button click i have to check for matches which are coming from database and remove matched words.
current solution is :
Dim strStreetName As String = txtHStreet.Text
For Each wordToRemove As DataRow In dsAbbreviation.Tables(0).Rows
If strStreetName.Contains(wordToRemove.Item("NAME")) Then
strStreetName = strStreetName.Replace(wordToRemove.Item("NAME"), "")
Exit For
End If
Next
but, I am looking for database side solution.
I think the following will work:
set #phrase = 'KENOX ROAD';
set #phrase = concat(' ', phrase, ' ')
select #phrase := replace(#phrase, concat(' ', w.word, ' '), ' '))
from words w;
set #phrase = trim(#phrase);
Your problem is a bit tricky because you seem to want the words to be identified and (unfortunately) MySQL does not have regex replace functionality. The above adds delimiters at the beginning and end and then does the replacement. Using variables like this is not a favorite approach, but I think it will work in this case.
MariaDB starts with 10.0.5 with REGEX - PCRE Regular Expressions
Mariadb REGEX Manual
MySQL does not natively support regexp replace. If you want to update an existing table you can try with something like this:
UPDATE
streets s INNER JOIN words w
ON INSTR(CONCAT(' ', s.name, ' '), CONCAT(' ', w.word, ' '))>0
SET
s.name = TRIM(
REPLACE(CONCAT(' ', s.name, ' '), CONCAT(' ', w.word, ' '), ' ')
);
and if you want to match and replace multiple words you have to re-run this update query until it doesn't find any more match. Please see a fiddle here. Not too clean, but it should do its work.
If you just want a SELECT, and you want it to support multiple words replace, I think there's no solution unless you use a programming language.

What would be a sql query to remove \n\r from the text?

I am using MySQL. My data has a column called text, which uses the TEXT data type.
There are several newlines for each record in this column. I want to remove all new lines with a sql query. How can I do that?
Try this one -
CREATE TABLE table1(column1 TEXT);
INSERT INTO table1 VALUES ('text1\r\ntext2
text3');
SELECT * FROM table1;
--------
text1
text2
text3
UPDATE table1 SET column1 = REPLACE(column1, '\r\n', '');
SELECT * FROM table1;
--------
text1text2text3
The previous suggestions did not work for me. It only seems to work if I had actually typed the \r and \n text in as text. I found the following to work well -
replace(replace([MyFieldName],char(13),''),char(10),'')
I also created a calculated field in my table which uses this formula. That way I can just reference that field in areas of my program that were breaking with the original field contents.
Given suggestion i.e. REPLACE(REPLACE(DBField, '\n', ''), '\r', '') won't work if there are invisible html code like \n \r. For that you have to use char code.
Example:
REPLACE(REPLACE(REPLACE(DBField, CHAR(10), ''), CHAR(13), ''), CHAR(9), '')
Try this
REPLACE(REPLACE(FIELD, '\n', ''), '\r', '')
You can use REPLACE(text,'\n\r',' ') for it.
i've tried all said here but neither worked for me, my DB is IBM Informix,
however i managed to solve the problem like this:
UPDATE personas SET foto_path = SUBSTRING(foto_path FROM 1 FOR LENGTH(foto_path) - 1);
Hope it helps other in similar situation.
The above version with single backslash cleared up some for me but also had to run this to clear up the rest.
REPLACE(REPLACE(FIELD, '\\n', ''), '\\r', '')

mysql - replace ' with single quote in a field

I'm not exactly sure what happened because I migrated from One server to another of the same spec and SQL...
Still in comments and titles the new database shows the characters ' instead of '
and I was wondering if I could ask for help in either replacing ' with '
or if it was simpler just deleting '
Thanks so much...
Steff
You could use MySQL's REPLACE method (look here):
UPDATE
Changed the statement to reflect the OP's naming:
UPDATE database1.vb_ppgal_albums
SET pp_photos = REPLACE(pp_photos, ''', '\'')
Good luck.
The following is the coding that I use to update double-quote in MySQL. I use the REPLACE function. The first parameter is the field_name that I want to have searched, the second is the escaping of the double quote (\") as the search string, followed by escaping of the escape character (\) followed by the double quote, which will insert into the field name (\"). In the table I will now have a measurement of '1/2\"' instead of '1/2"', which was my goal. I hope this helps. (PS, the Where clause is for show, you may not need it.)
UPDATE `table_name`
SET
`field_name` = REPLACE(`field_name`, '\"', '\\"')
WHERE `Id` > 125

Does the MySQL TRIM function not trim line breaks or carriage returns?

From my experiments, it does not appear to do so. If this is indeed true, what is the best method for removing line breaks? I'm currently experimenting with the parameters that TRIM accepts of the character to remove, starting with trimming \n and \r.
My line breaks were in the middle of the string, and I didn't have control over the source data. The following mysql command worked for me:
REPLACE(FIELD,'\r\n',' ')
Yes, Trim() will work in MySQL. You have two choices.
1) select it out:
select trim(BOTH '\n' from [field_name]) as field
If that doesn't work, try '\r', if that doesn't work, try '\n\r'.
2) replace the bad data in your table with an update...
update [table_name] set [field_name] = trim(BOTH '\n' from [field_name])
I recommend a select first to determine which line break you have (\r or \n).
The standard MySQL trim function is not like trim functions in any other languages I know as it only removes exact string matches, rather than any characters in the string. This stored function is more like a normal trim you'd find in PHP, or strip in python etc.
CREATE FUNCTION `multiTrim`(string varchar(1023),remove varchar(63)) RETURNS varchar(1023) CHARSET utf8
BEGIN
-- Remove trailing chars
WHILE length(string)>0 and remove LIKE concat('%',substring(string,-1),'%') DO
set string = substring(string,1,length(string)-1);
END WHILE;
-- Remove leading chars
WHILE length(string)>0 and remove LIKE concat('%',left(string,1),'%') DO
set string = substring(string,2);
END WHILE;
RETURN string;
END;
You should then be able to do:
select multiTrim(string,"\r\n\t ");
and it should remove all newlines, tabs and spaces.
select trim(both '\r\n' from FIELDNAME) from TABLE; should work if select trim(both '\n' from FIELDNAME) from TABLE; doesn't work.
Trim() in MySQL only removes spaces.
I don't believe there is a built-in way to remove all kinds of trailing and leading whitespace in MySQL, unless you repeatedly use Trim().
I suggest you use another language to clean up your current data and simply make sure your inputs are sanitized from now on.
i could only get it to work by making the char;
trim(both char(13) from fieldname)
select trim(both '\n' from FIELDNAME) from TABLE;
The answers above, when combined, work. A full example of replacing linebreaks at the beginning and end of the field looks like this:
UPDATE table SET field=REPLACE(field, field, TRIM(BOTH '\r\n' FROM field))
I faced the same issue with one of the fields. There is no perfect solution. In my case i was lucky that the length of the field was supposed to be 6. So i used a query like
update events set eventuniqueid = substring(eventuniqueid, 1, 6) where length(eventuniqueid) = 7;
You will just have to choose the best option based on your need. The replace '\n' and '\r\n' did not work for me and just ended up wasting my time.
REPLACE(FIELD,'\r\n',' ') works perfectly on MySql 5.1 database