I have problem using REPLACE() function on specific data. It doesn't match string occurrence that it should replace.
The string I want to replace is the following.
s:54:"Doctrine\Common\Collections\ArrayCollection_elements
It is stored in the following field
`definitions` longtext COLLATE utf8_unicode_ci NOT NULL COMMENT '(DC2Type:object)',
Here is the LIKE request which matches all rows that contain the string (notice \0 on the string):
SELECT `definitions`
FROM `entity_type`
WHERE `definitions` LIKE '%s:54:"\0Doctrine\\\\Common\\\\Collections\\\\ArrayCollection\0_elements%'
At the same time when I run the following request I get '0 rows affected' message and nothing is replaced:
UPDATE `entity_type`
SET `definitions` = REPLACE(
`definitions`,
's:54:"\0Doctrine\\\\Common\\\\Collections\\\\ArrayCollection\0_elements',
's:53:"\0Doctrine\\\\Common\\\\Collections\\\\ArrayCollection\0elements'
);
How should I modify the string to make REPLACE() match the text I need and replace it?
PS: Please don't blame me for what I'm trying to replace. it is not my fault :-)
If your "where condition" works, you can try with:
UPDATE `entity_type`
SET `definitions` = REPLACE(REPLACE(
`definitions`,
's:54:',
's:53:'),'ArrayCollection_elements','ArrayCollectionelements')
where `definitions` LIKE '%s:54:"\0Doctrine\\\\Common\\\\Collections\\\\ArrayCollection\0_elements%';
Related
I created a SET sql table, so a row can contain multiple values: Foo_1 Foo_2 Foo_3.
The above query run but it will update the the row and set just one value.
QueryType valid values are 1 2 or 3
"UPDATE Foo_status
SET type = 'Foo_%s',
status = %d
WHERE name ='%s'
", queryType.c_str(),status,GetName()
When i run the query: Let's assume that QueryType is 1, it's working.. my type row will have Foo_1, but when i run again the query and Foo has QueryType 2, it will remove Foo_1 and add Foo_2
How i can change my query so when i run the query it will continue to update values ?
Example:
Run Query
-Add Foo_1
Run Query
-Add Foo_2
Table struct
CREATE TABLE `Foo_status` (
`name` text NOT NULL,
`type` set('Foo_1','Foo_2','Foo_3') CHARACTER SET latin2 NOT NULL DEFAULT '',
`status` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I tried to search for an solution but without succes, that's i asked here.
Thanks!
Multiple set elements are specified using a comma-separated string. To add a new value, you have to concatenate a string beginning with comma.
"UPDATE Foo_status
SET type = CONCAT(type, ',Foo_%s'),
status = %d
WHERE name ='%s'
", queryType.c_str(),status,GetName()
To remove a value from a SET, use REPLACE():
"UPDATE Foo_status
SET type = REPLACE(type, 'Foo_%s', ''),
status = %d
WHERE name ='%s'
", queryType.c_str(),status,GetName()
It would be easier if you normalized your schema and used a table with a separate row for each type, instead of using the SET datatype. This would also allow you to add an index that would make searching for specific set values more efficient.
You can remove a set wirh this. Here written for select.
You can it also use for UPDATE.
You only must change the string to remove
select t,
trim( BOTH ',' FROM
replace (concat (',',t,','),',Foo_2,',',')) as new_t
from F;
Sample: http://www.sqlfiddle.com/#!9/a8b041/2
I have a table contains lots of column. Many columns contain NULL value. But while I'm trying to create CSV file from it, NULL is being replaced by '/N'. I want to set all the columns value to empty string instead of NULL so that I don't have to face problem with '/N'
You can use FIELDS ESCAPED BY clause along with SELECT query and specify an empty String or whitespace (' ') to get empty values instead of \N, e.g.:
SELECT * INTO file
FIELDS ESCAPED BY ''
LINES TERMINATED BY '\n'
FROM test_table;
Here's MySQL's documentation about it, this is what it says:
If the FIELDS ESCAPED BY character is empty, no characters are escaped
and NULL is output as NULL, not \N.
You can update all the columns and set to empty string instead of NULL, If you don't want to continue with NULL.
If you want to continue with NULL in DB, then export into a temp DB table and apply above logic...
First you need to update column default value with below query.
ALTER TABLE `table_name` CHANGE `column_name` `column_name` varchar(length) default '';
UPDATE `table_name` SET `column_name`='' where `column_name`='/N';
May this will help you.
You can use resultset metadata. Iterate through all the columns and check for null values.
ResultSet rsMain = stmt.executeQuery(selectQuery);
ResultSetMetaData rsmd = rsMain.getMetaData();
while(rsMain.next()){
for (int i = 1; i <=rsmd.getColumnCount(); i++) {
if(rsMain.wasNull())
{
sb.append('');// this is the string buffer that writes to the csv
sb.append(',');
}
}
}
You can update the table like this:
UPDATE yourTable
SET col1 = IFNULL(col1, ''),
col2 = IFNULL(col2, ''),
col3 = IFNULL(col3, ''),
...
Once you've done this, you should probably change the schema so that nulls aren't allowed and the default value is '', so you don't have to go through this again.
I have CSV file, contains date field that has either:
1. %Y-%m-%d
2. %m/%d/%Y
3. empty string
The code I use for importing:
LOAD DATA INFILE ...
SET EpStartDate = IFNULL (DATE(#v_EpStartDate), STR_TO_DATE(#v_EpStartDate, '%m/%d/%Y')),
...
But this code throws warning about every %m/%d/%Y date, and about each empty cell.
It's very important to me to show only crucial warnings, when the data is wrong, like if the date is 03/18/20095.
Any idea how to do that?
It's doable using custom function:
DROP FUNCTION IF EXISTS PARSE_DATE;
DELIMITER //
CREATE FUNCTION PARSE_DATE ( str VARCHAR(255) ) RETURNS DATE
BEGIN
IF str in ('',' ','.') THEN RETURN null;
ELSEIF str like '__/__/____' THEN RETURN STR_TO_DATE(str, '%m/%d/%Y');
ELSEIF str like '__-__-____' THEN RETURN STR_TO_DATE(str, '%m-%d-%Y');
ELSE RETURN DATE(str); /*may throw a warning*/
END IF;
END//
DELIMITER ;
Read the IFNULL function details here.enter link description here. The code
IFNULL(expr1, expr2)
returns expr1 if expr1 is NOT null, and expr2 if expr1 IS null.
So when the date variable is not empty, it is returned as it is (without checking for format, as that is done in expr2 in your code above) and when it is empty, it is checked against the date format.
Thus your program gives you warnings because you are checking for date formats on empty strings and at the same time input the non-empty strings without checking for their date format.
I have this SQL query and I wanted to insert the value of my bbcode_uid column into the replace statement
UPDATE `phpbb_posts`
SET `post_text` = REPLACE(post_text, '"]', '":*MY_BBCODE_UID*]')
is this possible?
The solution that I used
UPDATE `phpbb_posts`
SET `post_text` = REPLACE(post_text, '"]', CONCAT('":', bbcode_uid, ']'))
if there's better syntax, i'm interested
We have a database that has a bunch of records with some bad data in one column, in which an embedded editor escaped some stuff that shouldn't have been escaped and it's breaking generated links.
I want to run a query to replace the bad characters in all the records, but can't figure out how to do it. I found the replace() function in MySQL, but how can I use it inside a query?
For example, what would be the correct syntax if I wanted to replace the string < with an actual less-than angle bracket (<) in all records that have < in the articleItem column? Can it be done in a single query (i.e. select and replace all in one swoop), or do I have to do multiple queries? Even if it's multiple queries, how do I use replace() to do the replace on the value of a field on more than one record?
At a very generic level
UPDATE MyTable
SET StringColumn = REPLACE (StringColumn, 'SearchForThis', 'ReplaceWithThis')
WHERE SomeOtherColumn LIKE '%PATTERN%'
In your case you say these were escaped but since you don't specify how they were escaped, let's say they were escaped to GREATERTHAN
UPDATE MyTable
SET StringColumn = REPLACE (StringColumn, 'GREATERTHAN', '>')
WHERE articleItem LIKE '%GREATERTHAN%'
Since your query is actually going to be working inside the string, your WHERE clause doing its pattern matching is unlikely to improve any performance - it is actually going to generate more work for the server. Unless you have another WHERE clause member that is going to make this query perform better, you can simply do an update like this:
UPDATE MyTable
SET StringColumn = REPLACE (StringColumn, 'GREATERTHAN', '>')
You can also nest multiple REPLACE calls
UPDATE MyTable
SET StringColumn = REPLACE (REPLACE (StringColumn, 'GREATERTHAN', '>'), 'LESSTHAN', '<')
You can also do this when you select the data (as opposed to when you save it).
So instead of :
SELECT MyURLString From MyTable
You could do
SELECT REPLACE (MyURLString, 'GREATERTHAN', '>') as MyURLString From MyTable
UPDATE some_table SET some_field = REPLACE(some_field, '<', '<')
Check this
UPDATE some_table SET some_field = REPLACE("Column Name/String", 'Search String', 'Replace String')
Eg with sample string:
UPDATE some_table SET some_field = REPLACE("this is test string", 'test', 'sample')
EG with Column/Field Name:
UPDATE some_table SET some_field = REPLACE(columnName, 'test', 'sample')
you can write a stored procedure like this:
CREATE PROCEDURE sanitize_TABLE()
BEGIN
#replace space with underscore
UPDATE Table SET FieldName = REPLACE(FieldName," ","_") WHERE FieldName is not NULL;
#delete dot
UPDATE Table SET FieldName = REPLACE(FieldName,".","") WHERE FieldName is not NULL;
#delete (
UPDATE Table SET FieldName = REPLACE(FieldName,"(","") WHERE FieldName is not NULL;
#delete )
UPDATE Table SET FieldName = REPLACE(FieldName,")","") WHERE FieldName is not NULL;
#raplace or delete any char you want
#..........................
END
In this way you have modularized control over table.
You can also generalize stored procedure making it, parametric with table to sanitoze input parameter
This will help you.
UPDATE play_school_data SET title= REPLACE(title, "'", "'") WHERE title = "Elmer's Parade";
Result:
title = Elmer's Parade