Skip to content
Advertisement

How to separate values with Parse name in SQL Server

I have a value (500 , 850 , 65.5) as GivenUnitPrice and I want to separate these by making separate columns by PARSENAME

I have tried like this

PARSENAME(GivenUnitPrice, 3) as DB,
        PARSENAME(GivenUnitPrice, 2) as Owner,
        PARSENAME(GivenUnitPrice, 1) as Object

and the result is

DB   |     Owner      |      Object
NULL | 500 , 850 , 65 |       5

Advertisement

Answer

Seems you want to seperate the characters by commas but Parsename() function splits by dot character( e.g. decimal number 65.5 is also splitted as if seperate integers ), so yields wrong results for your case. It’s better to use replace(),substring() and charindex() together as :

with t as
(
select replace(replace('500 , 850 , 65.5',')',''),'(','') as GivenUnitPrice 
), t2 as
(
 select substring(GivenUnitPrice,1,charindex(',',GivenUnitPrice)-1) as db,
        substring(GivenUnitPrice,charindex(',',GivenUnitPrice)+1,len(GivenUnitPrice)) as owner_object       
   from t
)    
select db,
       substring(owner_object,1,charindex(',',owner_object)-1) as owner,
       substring(owner_object,charindex(',',owner_object)+1,len(owner_object)) as object
  from t2;

 db  owner  object
 500  850    65.5

Demo

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement