简体   繁体   English

如何使用T-SQL从字符串中获取数字部分?

[英]How to get the numeric part from a string using T-SQL?

I have the following string. 我有以下字符串。

Input
--------------
2030031469-NAI 

To get the numeric part, I am using the following script 要获取数字部分,我使用以下脚本

declare @str varchar(50)= '2030031469-NAI'

Select 
    @str
    ,SUBSTRING(@str, 1,  NULLIF(CHARINDEX('-', @str) - 1, -1))
        ,Left(@str,PATINDEX('%-%',@str)-1)

to get the following output 获得以下输出

Output: 
----------
2030031469

Is there any other easy/elegant way of doing the same? 有没有其他简单/优雅的方式做同样的事情?

select left(@str, patindex('%[^0-9]%', @str+'.') - 1)

Please check with this, i used in my project for extracting phone numbers 请检查一下,我在我的项目中用于提取电话号码

 CREATE Function [dbo].[RemoveNonNumericCharacters](@Temp VarChar(1000))
    Returns VarChar(1000)
    AS
    Begin

        While PatIndex('%[^0-9]%', @Temp) > 0
            Set @Temp = Stuff(@Temp, PatIndex('%[^0-9]%', @Temp), 1, '')

        Return @TEmp
    End

In case your string start with alphabet and end with number like ERT-123 如果您的字符串以字母开头并以ERT-123之类的数字结尾

you can use this query: 你可以使用这个查询:

 (select  substring(@str,patindex('%[0-9]%', @str),len(@str)))

To extract number from an unformatted string 从未格式化的字符串中提取数字

DECLARE @Text NVARCHAR(100)= 'extract only 23124R integer @#%%'
SELECT SUBSTRING(@Text, PATINDEX('%[0-9]%',@Text), PATINDEX('%[^0-9]%',SUBSTRING(@Text, PATINDEX('%[0-9]%',@Text), LEN(@Text)))-1) [ONLY_INT]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM