Search

Saturday, August 13, 2011

ParseName

PARSENAME retrieves parts of string delimited by dots. It is used to split DataBaseServer, DataBaseName, ObjectOwner and ObjectName but you can use it to split IP addresses, names etc
DECLARE @ParseString VARCHAR(100)
    SELECT @ParseString = 'DataBaseServer.DataBaseName.ObjectOwner.ObjectName'

    SELECT PARSENAME(@ParseString,4),
    PARSENAME(@ParseString,3),
    PARSENAME(@ParseString,2),
    PARSENAME(@ParseString,1)


    CREATE TABLE #Test (
   SomeField VARCHAR(49))

    INSERT INTO #Test
    VALUES ('aaa-bbbbb')

    INSERT INTO #Test
    VALUES ('ppppp-bbbbb')

    INSERT INTO #Test
    VALUES ('zzzz-xxxxx')

    --using PARSENAME
    SELECT PARSENAME(REPLACE(SomeField,'-','.'),2)
    FROM #Test


Another example:
CREATE TABLE BadData (FullName VARCHAR(20) NOT NULL);
    INSERT INTO BadData (FullName)
    SELECT 'Clinton, Bill' UNION ALL
    SELECT 'Johnson, Lyndon, B.' UNION ALL
    SELECT 'Bush, George, H.W.';


Split the names into 3 columns
Your output should be this: LastName FirstName MiddleInitial Clinton Bill Johnson Lyndon B. Bush George H.W.
SELECT FullName,PARSENAME(FullName2,NameLen+1) AS LastName,
    PARSENAME(FullName2,NameLen) AS FirstName,
    COALESCE(REPLACE(PARSENAME(FullName2,NameLen-1),'~','.'),'') AS MiddleInitial
    FROM(
    SELECT LEN(FullName) -LEN(REPLACE(FullName,',','')) AS NameLen,
    REPLACE(REPLACE(FullName,'.','~'),', ','.') AS FullName2,FullName
    FROM BadData) x


However there is one caveat when using the parsename function; if the string you are parsing contains more than 4 sections (3 dots), the function will return NULL.
SELECT PARSENAME('a.b.c.d', 1) -- Returns d
    SELECT PARSENAME('a.b.c.d.e', 1) -- Returns NULL


ParseName is a handy function to use, but you must be aware of what your data looks like.

1 comment:

  1. I have a sting '101|1|1|2|3|4|5|6|7|8|9|10##102|1|1|2|3|4|5|6|7|8|9|10' want to split in row column values like split with '##' for rows and | for columns

    Output
    id val1 val2 val3 val4 val5 val6 val7 val8 val9 val10
    101 1 2 3 4 5 6 7 8 9 10
    102 1 2 3 4 5 6 7 8 9 10

    ReplyDelete