Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using PARSENAME to find the last item in a list

I am using Parsename in SQL and would like to extract the last element in a list of items. I am using the following code.

Declare @string as varchar(1000)
set @string = '25.26.27.28'

SELECT PARSENAME(@string, 1)

This works and returns the value 28 as I expect. However if I expand my list past more than 4 items then the result returns a NULL. For example:

Declare @string2 as varchar(1000)
set @string2 = '25.26.27.28.29'

SELECT PARSENAME(@string2, 1)

I would expect this to return a value of 29 however only NULL is returned

I'm sure there is a simple explaination to this can anyone help?

like image 613
PhilC Avatar asked Feb 15 '12 16:02

PhilC


1 Answers

PARSENAME is designed specifically to parse an sql object name. The number of periods in the latter example exempt it from being such a name so the call correctly fails.

Instead

select right(@string2, charindex('.', reverse(@string2), 1) - 1)
like image 143
Alex K. Avatar answered Nov 08 '22 23:11

Alex K.