Get string between 2 characters that repeats several times in sql server

后端 未结 4 1441
执笔经年
执笔经年 2021-01-21 22:58

I need to extract multiple strings between 2 specific characters that repeats several times in a row. for example; these are 2 rows from my table:

id myString
         


        
4条回答
  •  广开言路
    2021-01-21 23:39

    If the string always follows the repeating pattern of '..(..)' one method to solve this uses a CSV Splitter function by Jeff Moden, replacing the second delimiter with the first delimiter, and getting only the second sets using modulo (%):

    select 
        Id
     , myString = x.item
    from t
      cross apply (
        select Item = ltrim(rtrim(i.Item))
          from [dbo].[delimitedsplit8K](replace(t.mystring,')','('),'(') as i
          where ItemNumber%2=0
          ) x
    

    test setup: http://rextester.com/DAI48471

    Added example input of 3,'jjj(kkk)ll(mmm)n(ooooo)pp(qq)rr'

    returns:

    +----+----------+
    | Id | myString |
    +----+----------+
    |  1 | bb       |
    |  1 | ffffd      |
    |  2 | ff       |
    |  2 | hhh      |
    |  3 | kkk      |
    |  3 | mmm      |
    |  3 | ooooo    |
    |  3 | qq       |
    +----+----------+
    

    splitting strings reference:

    • Tally OH! An Improved SQL 8K “CSV Splitter” Function - Jeff Moden
    • Splitting Strings : A Follow-Up - Aaron Bertrand
    • Split strings the right way – or the next best way - Aaron Bertrand
    • string_split() in SQL Server 2016 : Follow-Up #1 - Aaron Bertrand

提交回复
热议问题