How to extract this specific substring in SQL Server?

前端 未结 5 2272
慢半拍i
慢半拍i 2020-12-03 18:04

I have a string with a specific pattern:

23;chair,red [$3]

i.e., a number followed by a semicolon, then a name followed by a left square br

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 18:32

    select substring(your_field, CHARINDEX(';',your_field)+1 ,CHARINDEX('[',your_field)-CHARINDEX(';',your_field)-1) from your_table

    Can't get the others to work. I believe you just want what is in between ';' and '[' in all cases regardless of how long the string in between is. After specifying the field in the substring function, the second argument is the starting location of what you will extract. That is, where the ';' is + 1 (fourth position - the c), because you don't want to include ';'. The next argument takes the location of the '[' (position 14) and subtracts the location of the spot after the ';' (fourth position - this is why I now subtract 1 in the query). This basically says substring(field,location I want substring to begin, how long I want substring to be). I've used this same function in other cases. If some of the fields don't have ';' and '[', you'll want to filter those out in the "where" clause, but that's a little different than the question. If your ';' was say... ';;;', you would use 3 instead of 1 in the example. Hope this helps!

提交回复
热议问题