Home > Database > Mysql Tutorial > How to Extract Numeric Characters from MySQL Data for Accurate Comparisons?

How to Extract Numeric Characters from MySQL Data for Accurate Comparisons?

Patricia Arquette
Release: 2024-12-07 21:16:16
Original
394 people have browsed it

How to Extract Numeric Characters from MySQL Data for Accurate Comparisons?

Extracting Numeric Characters from MySQL Data for Accurate Comparisons

To compare against specific numerical values in a MySQL table, where database entries may contain non-numeric characters, a reliable method is required to strip out those non-numerals. While PHP functions like preg_replace offer a convenient solution, MySQL requires a native approach.

MySQL Function to Strip Non-Digits

To effectively perform this task, the following MySQL function can be created:

CREATE FUNCTION STRIP_NON_DIGIT(input VARCHAR(255))
RETURNS VARCHAR(255)
BEGIN
   DECLARE output   VARCHAR(255) DEFAULT '';
   DECLARE iterator INT          DEFAULT 1;
   WHILE iterator < (LENGTH(input) + 1) DO
      IF SUBSTRING(input, iterator, 1) IN ( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ) THEN
         SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
      END IF;
      SET iterator = iterator + 1;
   END WHILE;
   RETURN output;
END
Copy after login

Usage

To utilize the STRIP_NON_DIGIT function in a query, simply apply it to the target column as follows:

SELECT * FROM foo WHERE STRIP_NON_DIGIT(bar) = '12345';
Copy after login

This query will retrieve records where the bar column, after having its non-numeric characters removed, matches the user's input of '12345'.

The above is the detailed content of How to Extract Numeric Characters from MySQL Data for Accurate Comparisons?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template