Search code examples
sqlsql-serverreplacecharindex

Pulling specific terms from a string-SQL


I am having a column of Full name like:

Fullname
-----------------------
Joel (MD),Garris
Yong (MD),Park
Kristen (DO),Kenny
Jr, Jack (MD),Freimann
FirstName (title), LastName 

What I actually want is FirstName only. I have tried following but cant get the result.

I tried using CHARINDEX and SUBSTRING but still dint find any result:

Replace(SUBSTRING(@aa,1,(CHARINDEX('(',@aa))),',','')

Tried to pull title seperately and then tried to replace it by null:

Replace(FullName,SUBSTRING(Fullname, CHARINDEX('(',Fullname,0),CHARINDEX(')',Fullname,CHARINDEX('(',Fullname,0))),'')

Can anyone tell me what is going wrong in this?


Solution

  • Another sample that parse with PARSNAME

    declare @tb table (Fullname varchar(400))    
        Insert into @tb values ('Joel (MD),Garris')
        Insert into @tb values ('Yong (MD),Park')
        Insert into @tb values ('Kristen (DO),Kenny')
        Insert into @tb values ('Jr, Jack (MD),Freimann')
        Insert into @tb values ('FirstName (title), LastName')
    
    select PARSENAME(REPLACE(Fullname,'(','.'),2) from @tb 
    
    Joel 
    Yong 
    Kristen 
    Jr, Jack 
    FirstName