Thursday, November 16, 2017

SQL - Use PARSENAME function to extract individual parts from a string

Today I discovered a very cool feature in T-SQL from Microsoft SQL Server.
It happens (unfortunately) again and again that several records are written in a single column and one is forced to extract individual parts from it. So far, I have always written a SQL function of my own, but this is will be history from now on with the help of the PARSENAME function. :-)

See this examples. I think, this explains it very well:

DECLARE @exampleString nvarchar(max) = 'Test;Test1;Test2' 
SELECT PARSENAME(REPLACE(@exampleString,';','.'),1)

--Result: Test2

SELECT PARSENAME(REPLACE(@exampleString,';','.'),2)

--Result: Test1

SELECT PARSENAME(REPLACE(@exampleString,';','.'),3)

--Result: Test

No comments:

Post a Comment