Solved

split string sql

Posted on 2013-10-30
5
313 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
ID: 39611977
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
ID: 39612091
Thanks for the grade.  Good luck with your project.  -Jim
0
 

Author Comment

by:VBdotnet2005
ID: 39612106
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
ID: 39612209
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
ID: 39613331
>>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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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.
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

911 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

17 Experts available now in Live!

Get 1:1 Help Now