SQL - 提取可变长度字符串的数字部分

时间:2015-02-15 18:16:39

标签: mysql sql string extract patindex

以下是一个例子:

[U_TipTon] = 118.7-> 59.35; [U_Haulge] = 428.28-> 214.14

我需要在Tipton中提取118.7-> 59.35,在另一列中提取428.28-> 214.14作为U_Haulage。

字符串的长度是可变的,以及我的模式字的位置。

我正在尝试使用Patindex,但我找不到方法。

2 个答案:

答案 0 :(得分:1)

在MySQL中有SUBSTRING_INDEX,它根据分隔符提取子字符串:

select
  substring_index(substring_index(x, '[U_TipTon]=', -1), ';', 1) as TipTon
  ,substring_index(substring_index(x, '[U_Haulge]=', -1), ';', 1) as Haulge
from
 (
   select '[U_TipTon]=118.7->59.35;[U_Haulge]=428.28->214.14' as x
 ) as dt

编辑: 在MS SQL Server中,它更复杂:

select 
   substring(xHaulge, 1, charindex(';', xHaulge + ';')-1) as Haulge,
   substring(xTipTon, 1, charindex(';', xTipTon + ';')-1) as TipTon
from
 (
   select
      case when charindex('[U_Haulge]=', x) > 0 
           then substring(x, charindex('[U_Haulge]=', x) + len('[U_Haulge]='), 8000)
           else '' 
      end as xHaulge,
      case when charindex('[U_TipTon]=', x) > 0 
           then substring(x, charindex('[U_TipTon]=', x) + len('[U_TipTon]='), 8000) 
           else '' 
      end as xTipTon
   from 
    (
      select '[U_TipTon]=118.7->59.35;[U_Haulge]=428.28->214.14' as x
    ) as dt
 ) as dt

答案 1 :(得分:0)

解决方案是:

情况下          当charindex('Haulge',t.xField)> 0然后

substring(t.xField,charindex('Haulge',t.xField)+ 8,当charindex(';',substring(t.xField,charindex('Haulge',t.xField)+ 8,LEN时的情况(t.xField)))= 0                                                         那么LEN(t.xField)                                                         else charindex(';',substring(t.xField,charindex('Haulge',t.xField)+ 8,LEN(t.xField))) - 1结束)                                                         别的' - '结束[拖运价格] ,案件         当charindex('Tipton',t.xField)> 0然后

substring(t.xField,charindex('TipTon',t.xField)+ 8,当charindex(';',substring(t.xField,charindex('Tipton',t.xField)+ 8,LEN时的情况(t.xField)))= 0                                                         那么LEN(t.xField)                                                         else charindex(';',substring(t.xField,charindex('Tipton',t.xField)+ 8,LEN(t.xField))) - 1结束)                                                         别的' - '结束[提示价格] ,案件         当charindex('AItmPr',t.xField)> 0然后

substring(t.xField,charindex('AItmPr',t.xField)+ 8,当charindex(';',substring(t.xField,charindex('AItmPr',t.xField)+ 8,LEN时的情况(t.xField)))= 0                                                         那么LEN(t.xField)                                                         else charindex(';',substring(t.xField,charindex('AItmPr',t.xField)+ 8,LEN(t.xField))) - 1结束)                                                         别的' - '结束[附加价格]