Solved

split string sql

Posted on 2013-10-30
5
317 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

Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

Question has a verified solution.

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

     When we have to pass multiple rows of data to SQL Server, the developers either have to send one row at a time or come up with other workarounds to meet requirements like using XML to pass data, which is complex and tedious to use. There is a …
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

830 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