简体   繁体   中英

splitting string from one column and extracting one part of string to another column in sql

I use sql server 2008 r2. The problem started when one person entered data into the datebase in two different formats.

The table is: ( as u can notice there are FName and LName in column 'Title' but it should be in FName and LName columns respectively.

 Title                      FirstName         LastName
 -------------------------------------------------------------------
 Prasident Ena Enic          null              null    *(not ok)*
 Prasident                   Hana              Hanic   *(ok)*
 Prasident Jack Johnson      null              null    *(wrong)*

So I splitted string in Title into 3 parts ( Title , SFirstName and SLastName ) using the code below.

ltrim(SUBSTRING (title ,CHARINDEX(' ', title)+1,
charindex(' ',title+' ',charindex(' ',title)+1)-charindex(' ',title)-1)),
ltrim(substring(title, charindex(' ',title,charindex(' ',title)+1), len(title)))

and I got this type od table.

SplittedTitle   SplittedFirstName  SplittedLastName  FirstName    LastName  
-------------------------------------------------------------------------------
Prasident        Ena                 Enic              null         null
Prasident        Prasident           Prasident         Hana         Hanic
Prasident        Jack                Johnson           null         null

Now I have problem with nulls in FirstName and LastName . How can I transfer right data ( from SplittedFirstName and SplittedLastName) instead of nulls. I hope anyone got the point what my problem is.

Anyone have any idea? Which function should I use and how?

I think you want an update. You can do this with an updatable CTE:

with toupdate as (
      <your query here>
     )
update toupdate
    set FirstName = SplittedFirstName,
        LastName = SplittedLastName
    where FirstName is null and LastName is null;

Do you mean something like this:

x+IsNull(y,'')

which replaces y with empty string if it is null?

You can find more about this function here :

All you need to do now is,to run a update on that resultant table

UPDATE tablename  
SET   
FirstName = case when SplittedTitle <> SplittedFirstName  
                 then SplittedFirstName end,  
LastName = case when SplittedTitle <> SplittedLastName  
                then SplittedLastName end 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM