如何从SQL Server中的字符串中仅获取数字?

时间:2017-05-03 05:03:43

标签: sql-server formatting

我有字符串:

010234336. 

我想只返回如下数字:

Django

有谁知道如何格式化这个字符串?

4 个答案:

答案 0 :(得分:2)

试试这个

Select Replace('010-234-336-', '-', '')

如果您有其他字符串并且只想要数字部分,请尝试以下代码。

Declare @strAlphaNumeric varchar(256) = '010-abnasd234-336-'

DECLARE @intAlpha INT
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)

WHILE @intAlpha > 0
 BEGIN
    SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
    SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
 END

Select ISNULL(@strAlphaNumeric,0)

我得到了上述解决方案: - Query to get only numbers from a string

答案 1 :(得分:0)

SELECT CONVERT (INT,REPLACE('010-234-336-.','-',''))

答案 2 :(得分:0)

SELECT Replace('010-234-336-', '-', '')

如果需要,您也可以转换或转换为整数。

SELECT CAST(Replace('010-234-336-', '-', '') AS INT) as value

SELECT CONVERT(INT, Replace('010-234-336-', '-', '')) as value 

答案 3 :(得分:0)

这是我用来删除字符串中所有非数字字符的函数,但是将结果保留为字符串。这是因为我从入门开始就没有丢失任何零。

CREATE FUNCTION dbo.fnsStripToNumber
(
    @inString   varchar(500) = NULL
)
RETURNS varchar(500) AS
BEGIN

    /***********************************************************************
    Object      :   User Defined Scalar Function [dbo].[fnsStripToNumber]
    Script Date :   <date: 2016-04-20>
    Author      :   Just Me
    Description :   Remove all non-numeric characters from a string.
    Updates     :   2016-04-20 - JustMe
                        Updated the script for speed.
                        Moved the function to follow coding standards.
    Test Script :   
                    SELECT
                        ODS.dbo.fnsStripToNumber('ts45my12fnc098.     ') AS strNumber

    ***********************************************************************/

    DECLARE
        @strReturn  varchar(500) = '',
        @intEnPos   int          = 1
    --
    --  Loop through the string from beginning to end looking for any numbers.
    --
    WHILE @intEnPos > 0
    BEGIN
        --
        --  This is like a progressive update SELECT statement.
        --  The position of the next space is first found.
        --  This updated value is used in the next variable assignment to parse the
        --  string unit.
        --  The starting position for the next string unit is updated.
        --  Modify the string unit and update the return string.
        --
        SELECT
            @intEnPos = PATINDEX('%[0-9]%', @inString),
            @strReturn +=   (
                                CASE
                                    WHEN @intEnPos > 0 THEN SUBSTRING(@inString, @intEnPos, 1)
                                    ELSE ''
                                END
                            ),
            @inString = RIGHT(@inString, DATALENGTH(@inString) - @intEnPos)
    END
    --
    --  Return the proper cased string.
    --
    RETURN @strReturn

END;

GO