• edwardwill - Thursday, December 6, 2018 2:14 AM

    I hadn't come across this function, but I confess that I struggle to understand the utility of it.  If you amend the SELECT statement thus

    SELECTPARSENAME('MyDB.dbo.OrderLine', 3)

    it returns MyDB.  But then you knew that already, because you'd typed it in!  So in what circumstances might this return something you didn't already know ...

    The intended usage is a bit questionable to me as well. In fact I have used it for the intended purposes exactly never. It is however useful. You can leverage it as a very limited string splitter. I have used it to parse emails into multiple components. You can do something similar for URLs or other strings you need to parse. The limitation is a max number of 4 elements.

    Here is an example.


    declare @Email varchar(100) = 'sean.lange@somewhere.com'

    --First we replace any existing periods with a character sequence not found in (any reasonable) email address because PARSENAME uses the period as the delimiter
    SET @Email = replace(replace(@Email, '.', '^%^'), '@', '.')

    --We need to undo the replace to restablish the original periods
    select UserName = replace(PARSENAME(@Email, 2), '^%^', '.')
        , DomainName = replace(PARSENAME(@Email, 1), '^%^', '.')

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/