Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Splitting a column into multiple columns

Status
Not open for further replies.

mossbs

Programmer
Aug 19, 2008
102
GB
Hi guys,

I have a table with 1 column in that essentially holds 4 bits of information in it...
e.g.
Code:
COLUMN1 
547011 23 MUA 0.2 
547011 24 MUA 0.2 
547011 25 MUA 0.2 
547011 39 MUA 0.2

....what I need to do is to split this out into 4 columns using the spaces as the delimiter...

any ideas how i would go about doing this?

Cheers guys,

Dan
 
There is no built in split function in Sql Server but there are plenty of UDF's out on the web. Just search for SQL SERVER SPLIT FUNCTION and you should get lots of choices.

Simi
 

Cool cheers Simi, I'll have a look about see what i can come up with.

 
If the data ALWAYS is not more than 4 values:
Code:
DECLARE @Test TABLE (Column1 varchar(200))

INSERT INTO @Test VALUES('547011 23 MUA 0.2')
INSERT INTO @Test VALUES('547011 24 MUA 0.2')
INSERT INTO @Test VALUES('547011 25 MUA 0.2')
INSERT INTO @Test VALUES('547011 39 MUA 0.2')

SELECT REPLACE(PARSENAME(REPLACE(REPLACE(Column1,'.','_'), ' ','.'),4),'_','.') AS Test1,
       REPLACE(PARSENAME(REPLACE(REPLACE(Column1,'.','_'), ' ','.'),3),'_','.') AS Test2,
       REPLACE(PARSENAME(REPLACE(REPLACE(Column1,'.','_'), ' ','.'),2),'_','.') AS Test3,
       REPLACE(PARSENAME(REPLACE(REPLACE(Column1,'.','_'), ' ','.'),1),'_','.') AS Test4
FROM @Test

Borislav Borissov
VFP9 SP2, SQL Server 2000,2005 & 2008.
 
Brilliant Cheers Boris - did exactly what I needed.

Could you possibly break down how that works... just so I fully understand it...
 
Check what PARSENAME() did in BOL :)

But as I said this will work if you have 4 values to split.
If you have more this will NOT work.

With several REPLACES() here I convert dot to underscore and back to dot, because PARSENAME() uses dot as separator.

Borislav Borissov
VFP9 SP2, SQL Server 2000,2005 & 2008.
 
Boris,

If we only have a limited number of parts, then we may apply XML splitting as shown in this thread

But this may fail if there are some characters such as & in the string. In this case, I recommend the following blog post

PluralSight Learning Library
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top