0

I have a varchar string in SQL Server:

DECLARE @vStr VARCHAR(MAX) = ';ABC,DEF,+123456789,+987654321,0,0,0,0,0,+987654321,1110:'

For this string I want result like:

'+123456789,+987654321,0,0,0,0,0,+987654321'

DECLARE @vStr VARCHAR(MAX) = ';PQR,XYZ,+987654321,+987654321,0,0,0,0,0,+9876123456,5555:'

should generate result like:+987654321,+987654321,0,0,0,0,0,+9876123456

I am trying substring with left and len but it is not working.

UPDATE:

In general I do not want first two part of this comma separated string and also I do not want last part of the comma separated string.

7
  • do you have mix alpha + numeric case ? like ABC123, DEF123 ? Commented Mar 15, 2016 at 6:25
  • yes @Squirrel.. it is a possibility Commented Mar 15, 2016 at 6:26
  • What's the general rule? From the first string with + up to the last string with +? Commented Mar 15, 2016 at 6:28
  • so ABC123 is in or out of the result ? Commented Mar 15, 2016 at 6:30
  • @FelixPamittan General rule is I do not want first two values from coma separated string. For first string I do not want ";ABC" and "Def,". and I do not want last portion. i.e. 1110 in first example. I hope I have made my self clear Commented Mar 15, 2016 at 6:32

2 Answers 2

3
select  result = stuff(item, 1, charindex(',', item, charindex(',', item) + 1), '')
from
(
    -- exclude last item
    select  item = left(@vStr, len(@vStr) - charindex(',', reverse(@vStr)))
) d

explaination

  • the inner query is to exlude the last item. This is done by using reversing the string (reverse()) and then find the comma "," and then use LEFT() to get the left part up to the last comma

  • the 2 charindex() on the outer query is to find the 2nd comma

  • And then remove whatever up the 2nd comma using stuff()
Sign up to request clarification or add additional context in comments.

2 Comments

Brilliant solution! Would be better if you include some more explanation.
@Squirrel Thanks for this timely solution
0

Can you Please try this

select substring( substring (substring(@vStr,1,len(@vStr)),10,len(@vStr)),0,len(@vStr)-14 )

1 Comment

Your answer works for the both examples I have given above. But I have plenty of strings which I need to parse. See the general expected result I have updated in question. Your this solution does not work with Select @vStr = ';1GALQR,20111,19727328849,0,0,0,0,0,0,0,583424:'

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.