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
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
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
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.Simplest appraoch is to use with combination of LEFT() & CHARINDEX() :
SELECT LEFT(col, CHARINDEX('.', col + '.', CHARINDEX('.', col + '.') + 1 ) - 1)
FROM table t;
LEFT(TV_AB_Name, CHARINDEX('.', TV_AB_Name + '.', CHARINDEX('.', TV_AB_Name + '.') + 1 ) - 1)