Solved

split string sql

Posted on 2013-10-30
5
312 Views
Last Modified: 2013-10-30
I am using sql 2008

select debtorname from mytable

this returns Doe, John a

How can I split it to

debtorfirstname  debtorlastname
'John a '        'Doe'
0
Comment
Question by:VBdotnet2005
  • 3
5 Comments
 
LVL 65

Accepted Solution

by:
Jim Horn earned 500 total points
Comment Utility
Assuming every column has a single comma...
Declare @str varchar(100) = 'Doe, John a'

SELECT LEFT(@str, CHARINDEX (',', @str, 1)  - 1) as last_name, 
	RIGHT(@str, LEN(@str) - CHARINDEX (',', @str, 1) - 1 ) as first_name

Open in new window

0
 
LVL 65

Expert Comment

by:Jim Horn
Comment Utility
Thanks for the grade.  Good luck with your project.  -Jim
0
 

Author Comment

by:VBdotnet2005
Comment Utility
sorry, I hope it not too late.

What would happen if @str is blank or @str does not contain "."?  How should I handle it?  I am passing it from my aspx page.
0
 
LVL 65

Expert Comment

by:Jim Horn
Comment Utility
That really depends on what you think the values will be if there are no commas:  all first name, all last name, should reject for manual intervention..

If it's a single row it should be easy enough for your front-end to validate it.

If it's for a set, then there should be a WHERE CHARINDEX (',', @str, 1) <> 0 to validate that there was a comma in the first place.
0
 
LVL 48

Expert Comment

by:PortletPaul
Comment Utility
>>sorry, I hope it not too late.
well, I am, but below is an approach I would take.

note this trick, if searching for a particular string using charindex, add that string to the field value
CHARINDEX (','          , debtorname + ','           , 1)

this helps avoid getting negative numbers in subsequent functions such as

LEFT(debtorname, CHARINDEX (',', debtorname, 1)  - 1)

I also like to use CROSS APPLY for these calculations as the result of a cross apply is conveniently reusable by name in other calculations reducing effort and improving readability of code (IMHO)

    CREATE TABLE MyTable
    	([debtorname] varchar(80))
    ;
    	
    INSERT INTO MyTable
    	([debtorname])
    VALUES
    	('Flintstone, Fred'), 
    	('PortletPaul'),
    	('Doe, John a')
    ;

**Query 1**:

    SELECT
            last_name
          , first_name
          , debtorname
    FROM MyTable
    cross apply (select CHARINDEX (',', debtorname + ',', 1), len(debtorname) ) as ca1 (pos1, len1)
    cross apply (select
                        LEFT(debtorname, pos1  - 1)
                      , case when pos1 > len1 then null 
                             else RIGHT(debtorname, len1 - (pos1 + 1))
                        end 
                 ) as ca2 (last_name, first_name)
    
    	
    	
    

**[Results][2]**:
    
    |   LAST_NAME | FIRST_NAME |       DEBTORNAME |
    |-------------|------------|------------------|
    |  Flintstone |       Fred | Flintstone, Fred |
    | PortletPaul |     (null) |      PortletPaul |
    |         Doe |     John a |      Doe, John a |



  [1]: http://sqlfiddle.com/#!3/1bff5/2

Open in new window

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now