How "SQL Server" finds numbers in a string

Source: Internet
Author: User

Can be achieved by writing a custom function, the following provides two ways to solve:

1, through regular matching, find the number in the string, one by one to spell up

/*method One: one to find out*/CREATE FUNCTION [dbo].[Fun_getnumpart] ( @Str NVARCHAR(MAX) )RETURNS NVARCHAR(MAX) as    BEGIN        DECLARE @Start INT; DECLARE @End INT; DECLARE @Part NVARCHAR(MAX)        SET @Start = PATINDEX('%[0-9]%',@Str); SET @End = PATINDEX('%[0-9]%',SUBSTRING(@Str,@Start+1,LEN(@Str)- @Start)); SET @Part = SUBSTRING(@Str,@Start,1)          while  @End >0         BEGIN                 SET @Start = @start+@End                SET @Part = @Part+SUBSTRING(@Str,@Start,1)                       SET @End = PATINDEX('%[0-9]%',SUBSTRING(@Str,@Start+1,LEN(@Str)- @Start)); END                    RETURN  @Part; END;

2, through the regular reverse matching, find a string of non-numbers, one to remove

/*method Two: one to remove*/CREATE FUNCTION [dbo].[Fun_getnumpart]  ( @Str NVARCHAR(MAX) ) RETURNS NVARCHAR(MAX)    as   BEGIN        while PATINDEX('%[^0-9]%',@Str)>0       BEGIN           SET @Str=STUFF(@Str,PATINDEX('%[^0-9]%',@Str),1,"')--remove non-numeric characters    END       RETURN @Str END   

Effects such as:

Extended:

Can be replaced by the function of '%[0-9]% ' to the '%[a-z]% ', '%[-do]% ', change to find letters, find Chinese function

How "SQL Server" finds numbers in a string

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.