Home > Database > Mysql Tutorial > How Can I Extract Digits from Alphanumeric Strings in MySQL?

How Can I Extract Digits from Alphanumeric Strings in MySQL?

DDD
Release: 2025-01-09 16:46:42
Original
885 people have browsed it

How Can I Extract Digits from Alphanumeric Strings in MySQL?

Extract numbers from alphanumeric strings in MySQL

In database programming, extracting specific data from unstructured or mixed-type strings is a common task. MySQL provides a variety of functions and techniques for this purpose, including the ability to separate numbers from strings.

One way to extract a number from a string is to take advantage of MySQL's cast functionality. By using the CAST() function, you can implicitly convert a string to a numeric type, discarding non-numeric characters. For example, CAST('1234abc' AS UNSIGNED) returns 1234.

Another way is to use a custom function. You can create a reusable solution for extracting numbers by defining a function that iterates over the input string, checks the numeric value of each character, and concatenates the numbers into a new string. Consider the following function:

<code class="language-sql">CREATE FUNCTION `ExtractNumber`(in_string VARCHAR(50)) 
RETURNS INT
NO SQL
BEGIN
    DECLARE ctrNumber VARCHAR(50);
    DECLARE finNumber VARCHAR(50) DEFAULT '';
    DECLARE sChar VARCHAR(1);
    DECLARE inti INTEGER DEFAULT 1;

    IF LENGTH(in_string) > 0 THEN
        WHILE(inti <= LENGTH(in_string)) DO
            SET sChar = SUBSTR(in_string, inti, 1);
            IF sChar BETWEEN '0' AND '9' THEN
                SET finNumber = CONCAT(finNumber, sChar);
            END IF;
            SET inti = inti + 1;
        END WHILE;
        RETURN CAST(finNumber AS UNSIGNED);
    ELSE
        RETURN 0;
    END IF;    
END</code>
Copy after login

After defining a function, you can call it in a query to extract numbers from any string. For example, the following query will return the number 1234:

<code class="language-sql">SELECT ExtractNumber("abc1234def") AS number;</code>
Copy after login

The above is the detailed content of How Can I Extract Digits from Alphanumeric Strings in MySQL?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template