Jeff Smith Blog

Random Thoughts & Cartesian Products with Microsoft SQL Server

PARSENAME() - a simple way to parse (some) strings in SQL

Handy reminder: The PARSENAME() function can be useful for parsing small strings.  It returns parts 1-4 (working right to left) of a string, with each part delimited by periods.

For example:

PARSENAME('most.valuable.yak',3) returns “most”

PARSENAME('most.valuable.yak',1) returns “yak”

PARSENAME('most.valuable.yak',4) returns NULL

This can be handy when you need to parse an IP address, or very simple CSV strings.  Just REPLACE() the commas with periods and you are good to go.  Just remember you are working backwards.

This is a system function, designed to parse SQL Server 4-part names, so it only works with periods and strings with 4 parts.  But it can be useful!

Legacy Comments


Stoad
2003-10-16
re: PARSENAME()
LOL
I've already remembered this function... due to you.

glenn
2006-05-31
re: PARSENAME()
This was very helpful I did not know it was limited to 4 parts, you might want to state if you try to work with a string that has more than 4 parts you will recieve nulls for an answer