想要在Sql中区分字母数字列数据的数字和alpha值

时间:2013-03-22 19:41:06

标签: sql sql-server sql-server-2008

我想要不同的值形式给出示例

示例字符串:

Column1
---------
6A
6B
6C
7A
7B
7C

输出

Column1   Column2
---------------------
6           A
6           B
6           C
7           A
7           B
7           C 

有什么办法请帮忙

3 个答案:

答案 0 :(得分:3)

您可以使用PATINDEX

--DROP TABLE dbo.MyTbl;

CREATE TABLE dbo.MyTbl(column1 VARCHAR(200));
INSERT INTO dbo.MyTbl(column1)
VALUES
 ('123ab'),
 ('xxx'),
 ('13'),
 (''),
 ('4f');


SELECT LEFT(Column1,PATINDEX('%[^0-9]%',Column1+'x')-1), 
       SUBSTRING(Column1,PATINDEX('%[^0-9]%',Column1+'x'),LEN(Column1))
FROM dbo.MyTbl;

+'x'确保它可以处理数字后没有字符的情况。

答案 1 :(得分:0)

如果你有一个最大数字长度,那么你可以直接这样做:

select (case when numlen > 0 then cast(left(col1, numlen) as int) else 0 end) as column1,
       substring(col1, numlen+1, 100) as column2
from (select col1,
             (case when isnumeric(left(col1, 10)) = 1 then 10
                   when isnumeric(left(col1, 9)) = 1 then 9
                   when isnumeric(left(col1, 8)) = 1 then 8
                   when isnumeric(left(col1, 7)) = 1 then 7
                   when isnumeric(left(col1, 6)) = 1 then 6
                   when isnumeric(left(col1, 5)) = 1 then 5
                   when isnumeric(left(col1, 4)) = 1 then 4
                   when isnumeric(left(col1, 3)) = 1 then 3
                   when isnumeric(left(col1, 2)) = 1 then 2
                   when isnumeric(left(col1, 1)) = 1 then 1
                   else 0
              end) as Numlen
      from t
    ) t

答案 2 :(得分:0)

假设它以数字开头..

DECLARE @tab TABLE(Col VARCHAR(50))
INSERT INTO @tab 
VALUES('6A')
,('65BC'),('654CBA'),('7654ABCD')
,('76543BCDEF'),('765432CDEFGG')

SELECT *
FROM @tab

SELECT Col
,SUBSTRING(Col,1,(p0.num1-1)) AS Col1
,SUBSTRING(Col,p0.num1,LEN(Col)) AS Col2
FROM @tab
CROSS APPLY (
    SELECT 
    PATINDEX('%[^0-9]%',Col) AS num1)p0