Thursday, January 9, 2014

SQL server PARSENAME function

ref: http://www.sqlteam.com/article/using-the-parsename-function-to-split-delimited-data

This function basically split a string by delimiter "." and can fetch any of section of the string by position number (count starting from write hand side ).
For real life implementation we can have delimiter like "," or "|" in that case just replace those by "." first then you can use this function easily.

Sample code:

Declare @ObjectName nVarChar(1000)
Set @ObjectName = 'HeadOfficeSQL1.Northwind.dbo.Authors'

SELECT
        PARSENAME(@ObjectName, 4) as Server,
        PARSENAME(@ObjectName, 3) as DB,
        PARSENAME(@ObjectName, 2) as Owner,
        PARSENAME(@ObjectName, 1) as Object,
        PARSENAME('sss.dd',1)

Result:

Server                        DB          Owner  Object    (No column name)
HeadOfficeSQL1    Northwind    dbo    Authors    dd

No comments:

Post a Comment