在sql server中提取pattern1和pattern2之间的字符串

时间:2015-09-21 08:51:00

标签: sql-server-2012

列(c1)中的数据:
some_datadata1 / By_User / some_other_other_data1 / somedate1
some_datadata2 / By_User / some_other_other_data2 / somedate2
some_datadata3 / By_User / some_other_other_data3 / somedate3
some_datadata4 / By_User / some_other_other_data4 / somedate4

需要输出:
some_other_data1
some_other_data2
some_other_data3
some_other_data4

我正在寻找一个查询

我试过以下但没有工作:

select col1,
       substring(col1,charindex('By User/',col1)+len('By User/'),
         charindex('/',col1)-charindex('By User/',col1)-len('By User/')) 
from tablename

1 个答案:

答案 0 :(得分:0)

最好在应用程序代码中拆分字符串。

但是,如果您别无选择,可以使用LEFT,因为pattern1是字符串左侧的第一个:

Select col1, LEFT(col1, CHARINDEX('By_User/',col1) -2)
From (values ('some_datadata1/By_User/some_other_other_data1/somedate1')
    , ('some_datadata2/By_User/some_other_other_data2/somedate2')
    , ('some_datadata3/By_User/some_other_other_data3/somedate3')
    , ('some_datadata4/By_User/some_other_other_data4/somedate4')) as string(col1)

如果你想要模式3,第二个CHARINDEX需要开始寻找/在第二个模式的位置之后:

Select col1, left(col1, CHARINDEX('By_User/',col1) -2)
    , SUBSTRING(col1, CHARINDEX('By_User/',col1) + len('By_User/'), 
        CHARINDEX('/',col1, CHARINDEX('By_User/',col1) + len('By_User/')) 
        - CHARINDEX('By_User/',col1) - len('By_User/')
        )
From (values ('some_datadata1/By_User/some_other_other_data1/somedate1')
    , ('some_datadata2/By_User/some_other_other_data2/somedate2')
    , ('some_datadata3/By_User/some_other_other_data3/somedate3')
    , ('some_datadata4/By_User/some_other_other_data4/somedate4')) as string(col1)