1

Using the newest SQL update and String Split Function how do I insert the split data back into my table?

select be.*, SS.value
from b2bemployee be
outer apply string_split(firstname, ' ') AS SS
where id=2319

Using that I split my FirstName column into two values and the data is returned on two separate rows. I am trying to insert this data back into my table as updatedfirstname (before the space) and updatedlastname (after the space)

1

3 Answers 3

3

The Split functions can be slow, especially with larger tables.

Consider ParseName(), for example

Declare @String varchar(25) = 'John Smith 999-11-1234'
Select FirstName=PARSENAME(Replace(@String,' ','.'),3)
      ,LastName =PARSENAME(Replace(@String,' ','.'),2)
      ,SSN      =PARSENAME(Replace(@String,' ','.'),1)

--Returns--
FirstName   LastName    SSN
John        Smith       999-11-1234

So, in your case, and assuming your delimiter is a space AND your field looks like "Jame Smith"

Select FirstName=PARSENAME(Replace(YourFieldName,' ','.'),2)
      ,LastName =PARSENAME(Replace(YourFieldName,' ','.'),1)
Sign up to request clarification or add additional context in comments.

2 Comments

Just be careful with this if you are going to parse out more than 4 delimiters.
@dfundako Agreed, I've made assumptions in the past and I was wrong on a cosmic scale. This assumption I could live with
2

I think this will work instead:

Create Table #Test (Value Varchar(8000), LeftPart Varchar(8000), RightPart Varchar(8000))
Insert #Test Values ('Joe Cool', '', '')
Insert #Test Values ('John Doe', '', '')


Update #Test Set LeftPart = Substring(Value, 1, Charindex(' ', Value) - 1), RightPart = Substring(Value, Charindex(' ', Value) + 1, 8000) From #Test
Select * From #Test

Also note that unless you plan to drop the full field after the split, this is a good case for computed columns.

Comments

0

If you want to use STRING_SPLIT (the ways with PARSENAME and SUBSTRING are more adequate for this situation) you need to do something like this:

;WITH cte AS (
SELECT  be.*,
        SS.value as FN, 
        ROW_NUMBER() OVER (PARTITION BY be.id ORDER BY (SELECT 1)) as RN
FROM b2bemployee be 
OUTER APPLY STRING_SPLIT(be.firstname, ' ') as SS
WHERE be.id=2319
)

SELECT  c1.*,
        c2.FN
FROM cte c1
LEFT JOIN cte c2
    ON c1.RN+1 = c2.RN
WHERE c1.RN = 1

I would suggest to use LEFT and RIGHT

SELECT  be.*,
        RIGHT(be.firstname,CHARINDEX(' ',be.firstname)) as updatedfirstname ,
        LEFT(be.firstname,LEN(be.firstname) - CHARINDEX(' ',be.firstname)-1) as updatedlastname 
FROM b2bemployee be 
WHERE be.id=2319

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.