1

I know to do parts of it but not all of it, lets say my table name is REV and column name is DESCR and it has a value like

R&B , Semiprivate 2 Beds , Medical/Surgical/GYN

i use

SELECT  DESCR, LEFT(DESCR, Charindex(',', DESCR)),  SUBSTRING(DESCR, CHARINDEX(',', DESCR) + 1, LEN(DESCR)) from REV

i get 'R&B ,' in one column and 'Semiprivate 2 Beds , Medical/Surgical/GYN' in another column in the above select statement but i dont know how to selesct the strings from teh second comma onwards

what i like to return is 'R&B' in one column without the comma and 'Semiprivate 2 Beds' in another column and 'Medical/Surgical/GYN' so on

basically select test between commas and when there is no comma it should be blank

1

2 Answers 2

2

This should work:

  SELECT 
  LEFT(DESCR, CHARINDEX(',', DESCR)-1), 
  SUBSTRING(DESCR, CHARINDEX(',', DESCR)+1, CHARINDEX(',', DESCR, CHARINDEX(',', DESCR)+1) -  CHARINDEX(',', DESCR) -1 ),
  RIGHT(DESCR, CHARINDEX(',', REVERSE(DESCR))-1)
  FROM REV
Sign up to request clarification or add additional context in comments.

Comments

1

This should work:

SELECT 
  LEFT(DESCR, CHARINDEX(',', DESCR)-1), 
  SUBSTRING(DESCR, CHARINDEX(',', DESCR)+1, LEN(DESCR)-CHARINDEX(',', DESCR)-CHARINDEX(',',REVERSE(DESCR ))),
  RIGHT(DESCR, CHARINDEX(',', REVERSE(DESCR))-1)  
FROM REV

Sample SQL Fiddle

This will split the string, but leave blank at the beginning and end of the strings, you can use LTRIMand RTRIMto trim away the blanks.

There might be better ways to do this though; see the article Split strings the right way – or the next best way by Aaron Bertrand at (that Andrew mentioned in a comment).

2 Comments

The 1st and 3rd column in the select works but the middle column is not extracting it correctly it seems to be breaking. e.g: 'Hospital, Swing Beds, Interim-First Claim' comes out as 'Hospital' and 'Swing beds, Interi' and 'Interim-First Claim'. the second column is not coming out correclty
@user176047 I made some changes and added a sample SQL Fiddle. It should be more correct now, but it will only handle a string with two commas and split it into three parts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.