0

could you please help in getting the below sub string.

I have values like

1.1
1.10.1
1.2.2.1

expected output (need to exclude the digits after the second dot)

1.1
1.10
1.2
3
  • 2
    What have you tried so far? Commented Jan 16, 2020 at 14:55
  • What version of sql server are you on? Commented Jan 16, 2020 at 14:58
  • SELECT LEFT(yourstring, CHARINDEX('.', yourstring, CHARINDEX('.', yourstring)+1)-1); Commented Jan 16, 2020 at 15:01

2 Answers 2

3

Here is one approach that demonstrates the use of a CROSS APPLY and a little XML

Example

Declare @YourTable Table ([SomeCol] varchar(50))  Insert Into @YourTable Values 
 ('1.1')
,('1.10.1')
,('1.2.2.1')

Select A.* 
      ,NewValue=concat(
               XMLData.value('/x[1]','varchar(50)')
               ,'.'+XMLData.value('/x[2]','varchar(50)')
               )
 From  @YourTable A
 Cross Apply (  values (Cast('<x>' + replace(SomeCol,'.','</x><x>')+'</x>' as xml)) ) B(XMLData)

Returns

SomeCol   NewValue
1.1       1.1
1.10.1    1.10
1.2.2.1   1.2

EDIT - Just another option using parsename()

Select A.* 
      ,NewValue=reverse(parsename(reverse(SomeCol),2)
              +'.'
              +parsename(reverse(SomeCol),1)
              )
From  @YourTable A
Sign up to request clarification or add additional context in comments.

5 Comments

SELECT LEFT(yourstring, CHARINDEX('.', yourstring, CHARINDEX('.', yourstring)+1)-1);
Perfect, Thank you very much
reverse... that is a sneaky way of shoehorning parsename() into this. I love it. I was trying to make STRING_SPLIT() and STRING_AGG() to work here, but there is no way to guarantee order in the output which is a HUGE disappointment.
@JNevill Ups, i answered it this way, in SqlFiddle it looked fine...
@Turo string_split() may work 99.9999% of the time with a small sample, but there is no GTD of the sequence. This is a tragic omission from string_split().
0

Simplest appraoch is to use with combination of LEFT() & CHARINDEX() :

SELECT LEFT(col, CHARINDEX('.', col + '.', CHARINDEX('.', col + '.') + 1 ) - 1)
FROM table t;

5 Comments

this wont work for 1st string (1.1) where you have olny 1 occurence of .
LEFT(TV_AB_Name, case when CHARINDEX('.', TV_AB_Name, CHARINDEX('.', TV_AB_Name)+1) = 0 then len(TV_AB_Name) else CHARINDEX('.', TV_AB_Name, CHARINDEX('.', TV_AB_Name)+1) - 1 end )
please review and confirm
@Surya. . You don't need case expression for this. Use LEFT(TV_AB_Name, CHARINDEX('.', TV_AB_Name + '.', CHARINDEX('.', TV_AB_Name + '.') + 1 ) - 1)
For my requirement the logic without case is not working. the one with case which i sent is working fine. Thank you very much

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.