从字符串中提取大小(数字)

时间:2012-07-19 00:50:40

标签: sql sql-server string tsql string-parsing

我的表中的列的值存储为

HX CAP SCR GD5 1/2-13 X 3 3/4
HX CAP SCR GD8 1/2-13 X 4 1/4 
HX CAP SCR Grade 5 1/2-13 X 5 1/2
HX CAP SCR Grade 8 1/2-13 X 6 1/2

现在,我需要将这些值存储到另一个表中,如

CATEGORY               SIZE
HX CAP SCR GD5         1/2-13 X 3 3/4
HX CAP SCR GD8         1/2-13 X 4 1/4
HX CAP SCR Grade 5     1/2-13 X 5 1/2
HX CAP SCR Grade 8     1/2-13 X 6 1/2

我需要将类别与大小值分开。

This is what I have so far, but it is not working the GD5 and GR8 are part of the category column.

SELECT  CustDesc
        ,'??????' as Category
        ,SUBSTRING(CustDesc,PatIndex('%[0-9.-]%', CustDesc),8000) as Size   
FROM [##CustParts]

以上查询的结果

CustDesc                    Category    Size
HX CAP SCR GD5 1/2-13 X 3   ??????          5 1/2-13 X 3 

Plz让我知道执行此操作的查询是什么....

3 个答案:

答案 0 :(得分:1)

你需要制定一个看似合理的规则。例如,看起来大小在“X”之前的第一个空格之后开始。我们可以在SQL Server中使用(原始)字符串函数:

select ltrim(rtrim(left(val, pos1 - spacebefore))) as product,
     substring(val, pos1 - spacebefore + 1, 1000) as size
from (select t.*, charindex(' ', reverse(left(val, pos1-1))) as spacebefore
      from (select t.*,
                   charindex(' X ', val) as pos1
            from (select 'abce 15/3 x 2' as val) t
           ) t
     ) t

答案 1 :(得分:0)

根据您的示例,它看起来数字1是您解析每个元组中的值的引用。研究tsql的SQL CHARINDEX命令 - 在字符串中查找文本的位置

还有更多要解析的值吗?请提供更好的解析数据横截面。 - thx

答案 2 :(得分:0)

如果你的字符串总是包含字符“1/2”,那么这将完美地运作。

CREATE TABLE #tbl(col1 varchar(200))

INSERT INTO #tbl 
VALUES('HX CAP SCR GD5 1/2-13 X 3 3/4'),
('HX CAP SCR GD8 1/2-13 X 4 1/4'),
('HX CAP SCR Grade 5 1/2-13 X 5 1/2'),
('HX CAP SCR Grade 8 1/2-13 X 6 1/2')

select Left(col1,CHARINDEX('1/2',col1,1)-1),RIGHT(col1,len(col1)-(CHARINDEX('1/2',col1,1)-1)) from #tbl