Get the text between two "-"s for each row in SQL Server

dauxcl2d  于 2023-05-28  发布在  SQL Server
关注(0)|答案(2)|浏览(155)

Can someone please help me with trimming the below sample texts in SQL Server? I am looking to get the data between the two '-' (some rows do not have a '-' ).

  1. AB DCE
  2. CM-AB DCE -228
  3. ABC
  4. CM-AB DCE-214
  5. CJ-ABC-228

The output expected is:

  1. AB DCE
  2. AB DCE
  3. ABC
  4. AB DCE
  5. ABC

I tried:

  1. select substring(mycol, 4, charindex('-', mycol, 12) )

But the results are not accurate.

1yjd4xko

1yjd4xko1#

If you gather the position of your first symbol, and the position of your second symbol with CHARINDEX , you can extract what's contained inbetween with SUBSTRING .

  1. WITH cte AS (
  2. SELECT *,
  3. CHARINDEX('-', txt) AS startidx,
  4. CHARINDEX('-', txt, CHARINDEX('-', txt)+1) AS endidx
  5. FROM tab
  6. )
  7. SELECT SUBSTRING(txt,
  8. CASE WHEN startidx > 0 THEN startidx+1 ELSE 0 END,
  9. CASE WHEN startidx > 0 THEN endidx-startidx-1 ELSE LEN(txt) END) AS txt
  10. FROM cte

Output:

txt
AB DC
AB DCE
AB
AB DCE
ABC

Check the demo here .

展开查看全部
wz8daaqr

wz8daaqr2#

seems like the question has been answered here

https://www.webcodeexpert.com/2016/08/sql-server-query-to-get-string-between.html

  1. SELECT SUBSTRING(txt,CHARINDEX('-',txt)+1,
  2. (((LEN(txt))-CHARINDEX('-',REVERSE(txt)))-CHARINDEX('-',txt)))
  3. AS Result FROM tab

相关问题