Home > Database > Mysql Tutorial > How Can I Extract Numbers from Alphanumeric Strings in SQL?

How Can I Extract Numbers from Alphanumeric Strings in SQL?

Linda Hamilton
Release: 2025-01-21 01:51:08
Original
499 people have browsed it

How Can I Extract Numbers from Alphanumeric Strings in SQL?

Extract numbers from alphanumeric string in SQL

Question:

You have some strings containing alphanumeric characters and you need to extract only the numeric values. For example, given the following string:

  • 003Preliminary Examination Plan
  • Coordination005
  • Balance1000sheet

You wish to search for:

  • 003
  • 005
  • 1000

Solution:

To extract numbers from a string using SQL, you can use user-defined functions (UDFs). Create the following UDF:

<code class="language-sql">CREATE FUNCTION dbo.udf_GetNumeric
(
  @strAlphaNumeric VARCHAR(256)
)
RETURNS VARCHAR(256)
AS
BEGIN
  DECLARE @intAlpha INT
  SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
  BEGIN
    WHILE @intAlpha > 0
    BEGIN
      SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
      SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
    END
  END
  RETURN ISNULL(TRIM(@strAlphaNumeric), '0')
END
GO</code>
Copy after login

Usage:

After creating the UDF, you can use it to extract numbers from a string:

<code class="language-sql">SELECT dbo.udf_GetNumeric(column_name)
FROM table_name</code>
Copy after login

For example:

<code class="language-sql">SELECT dbo.udf_GetNumeric('003Preliminary Examination Plan')</code>
Copy after login

Reference:

Note:

This solution outputs numbers as strings. If you need integers, you can use the CAST() function to convert them. The above code has been simplified to avoid unnecessary complex logic and ensure that the function always returns a value.

The above is the detailed content of How Can I Extract Numbers from Alphanumeric Strings in SQL?. 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