MySQL Forums
Forum List  »  Newbie

Re: how to replace hex in varchar field
Posted by: Rick James
Date: May 21, 2011 05:53PM

This task is best done with the aid of some programming language. Here are some clues of what can be done in SQL:

mysql> CREATE TABLE f420270 (s VARCHAR(22) CHARACTER SET latin1);
mysql> INSERT INTO f420270 (s) VALUE (CONCAT('A', UNHEX('92'), 'C'))
mysql> INSERT INTO f420270 (s) VALUE ('This is ok');
mysql> SELECT s, HEX(s) FROM f420270;
+------------+----------------------+
| s          | HEX(s)               |
+------------+----------------------+
| A'C        | 419243               |  <-- see the 92
| This is ok | 54686973206973206F6B |
+------------+----------------------+

# Find rows with any 8-bit chars:
mysql> SELECT * FROM f420270 WHERE HEX(s) RLIKE '^(..)*[8-F].';
+------+
| s    |
+------+
| A'C  |
+------+

# Or look only for your naughty char:
mysql> SELECT * FROM f420270 WHERE s RLIKE UNHEX('92');
+------+
| s    |
+------+
| A'C  |
+------+

# chars before the first naughty:
mysql> SELECT s, LENGTH(SUBSTRING_INDEX(s, UNHEX('92'), 1)) FROM f420270;
+------------+--------------------------------------------+
| s          | LENGTH(SUBSTRING_INDEX(s, UNHEX('92'), 1)) |
+------------+--------------------------------------------+
| A'C        |                                          1 |
| This is ok |                                         10 |
+------------+--------------------------------------------+

That LENGTH(SUBSTRING_INDEX(...)) is a start at picking out the bad char using UPDATE ... s=REPLACE(...).

If hex 92 is your only problem, then let's continue:
First, I want to add a row with two naughties, so as to verify that both get fixed.
mysql> INSERT INTO f420270 (s) VALUE (CONCAT('a', unhex('92'), 'c', unhex('92'), 'e'));

mysql> UPDATE f420270 SET s=REPLACE(s, UNHEX('92'), '-');
Query OK, 1 row affected (0.12 sec)
Rows matched: 3  Changed: 1  Warnings: 0

mysql> SELECT * FROM f420270;
+------------+
| s          |
+------------+
| A-C        |
| This is ok |
| a-c-e      |
+------------+
So, maybe all you need is
UPDATE tblname SET colname = REPLACE(colname, UNHEX('92'), '');

Options: ReplyQuote


Subject
Written By
Posted
Re: how to replace hex in varchar field
May 21, 2011 05:53PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.