我需要将字符串中的所有数字和字符分开

时间:2011-06-20 08:01:20

标签: sql sql-server

请帮我解决上述问题。

字符串如下所示:'AB78KH013Hj9' 我应该这样:num:780139                            炭:ABKHHJ

6 个答案:

答案 0 :(得分:1)

试试这个

Declare @s varchar(100),@result varchar(100)
set @s='as4khd0939sdf78' 
set @result=''

select
    @result=@result+
            case when number like '[0-9]' then number else '' end from 
    (
         select substring(@s,number,1) as number from 
        (
            select number from master..spt_values 
            where type='p' and number between 1 and len(@s)
        ) as t
    ) as t 
select @result as only_numbers 

您还可以使用用户定义的功能 请参阅这些链接 http://beyondrelational.com/blogs/madhivanan/archive/2007/12/18/extract-only-numbers-from-a-string.aspx http://blog.sqlauthority.com/2007/04/11/sql-server-udf-user-defined-function-to-extract-only-numbers-from-string/

答案 1 :(得分:0)

string numPart, charPart;
foreach(char c in input)
{
    if(c.islpha())
    {
        charPart = charPart + c;
    }
    else if (c.isnumber())
    {
        numPart = numPart + c;
    }
}

答案 2 :(得分:0)

试试这个:

DECLARE @s varchar(max) = 'AB78KH013Hj9';
SELECT REPLACE(REPLACE(REPLACE(@s, '0', ''), '1', ''), '2', '') [string]
    , REPLACE(REPLACE(REPLACE(@s, 'a', ''), 'b', ''), 'c', '') [number]

答案 3 :(得分:0)

DECLARE @NumStr varchar(1000)
SET @NumStr = 'AB78KH013Hj9';

BEGIN
WHILE PATINDEX('%[^0-9]%',@NumStr)> 0
    SET @NumStr = REPLACE(@NumStr,SUBSTRING(@NumStr,PATINDEX('%[^0-9]%',@NumStr),1),'')
END

PRINT @NumStr 

答案 4 :(得分:0)

WITH
  filter AS
(
SELECT
  LEN('AB78KH013Hj9') AS remaining,
      'AB78KH013Hj9'  AS input,
  ''                  AS numeric,
  ''                  AS alpha

UNION ALL

SELECT
  remaining - 1,
  RIGHT(input, remaining - 1),
  CASE WHEN PATINDEX('%[^0-9]%', LEFT(input, 1)) > 0 THEN numeric ELSE numeric + LEFT(input, 1) END,
  CASE WHEN PATINDEX('%[^0-9]%', LEFT(input, 1)) > 0 THEN alpha + LEFT(input, 1) ELSE alpha END
FROM
  filter
)


SELECT numeric, alpha FROM filter WHERE remaining = 0

答案 5 :(得分:0)

DECLARE @string varchar(20),@Num varchar(20),@str varchar(20),@i AS INT
SET @string = 'AB78KH013Hj9';
SET @i = 0
SET @num = @string
SET @str = @string

WHILE @i <= len(@string)
BEGIN
    SET @str =  REPLACE(@str,SUBSTRING(@str,PATINDEX('%[^a-z]%',@str),1),'')
    SET @num =  REPLACE(@num,SUBSTRING(@num,PATINDEX('%[^0-9]%',@num),1),'')
    SET @i = @i + 1
END

PRINT @Num
PRINT @str