Solved

split string sql

Posted on 2013-10-30
5
320 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
5 Comments
 
LVL 66

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 66

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 66

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 49

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

Simplifying Server Workload Migrations

This use case outlines the migration challenges that organizations face and how the Acronis AnyData Engine supports physical-to-physical (P2P), physical-to-virtual (P2V), virtual to physical (V2P), and cross-virtual (V2V) migration scenarios to address these challenges.

Question has a verified solution.

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

Long way back, we had to take help from third party tools in order to encrypt and decrypt data.  Gradually Microsoft understood the need for this feature and started to implement it by building functionality into SQL Server. Finally, with SQL 2008, …
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

687 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