Infolink

 

Search This Blog

Oct 27, 2012

PARSENAME in Sql

DECLARE @t TABLE (A varchar(25))

INSERT @t values ('77.88.99.100') 

SELECT
  PARSENAME(A,1) AS 'First selected'
, PARSENAME(A,2) AS '2nd selected'
, PARSENAME(A,3) AS '3rd selected'
, PARSENAME(A,4) AS '4th selected'
 from @t

The question is: (select 1)

a. Are the values returned  First selected 77,  2nd selected 88,3rd selected 99,4th selected 100'

b. Are the values returned first selected 100,  2nd selected 99,3rd selected 88, 4th selected 77

c. No values are returned.

The Answer  :

b. Are the values returned first selected 100,  2nd selected 99,3rd selected 88, 4th selected 77

Another Example

 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!

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...