SQL query to split concatenated string into separate parts

时间:2016-07-11 19:46:01

标签: ms-access

Need your expertise in one query: I need a SQL query to split concatenated string into separate parts. My data looks like this

Name  Location           Name Link   Location Link  Final Location     Material
C50   2398::3276::3916   GA-4-2      58::52::24     558::352::324::70  93530

and i want output like this:

Name  Location           Name Link   Location Link  Final Location     Material
C50   2398               GA-4-2      58             558                93530
C50   3276               GA-4-2      52             352                93530
C50   3916               GA-4-2      24             324                93530
C50                      GA-4-2                     70                 93530

2 个答案:

答案 0 :(得分:1)

Grab a Split function from the internet that includes an IDENTITY column and use the function on each of the concatenated columns to get a table for each of them, and JOIN all the tables on the Identity column.

答案 1 :(得分:0)

As I said before, this design is incredibly painful to work with. Please consider fixing it or you will be forced to continue fighting a losing battle against your database design.

Since you state the number of elements are fixed you can use PARSENAME to split these values. Here is how this might work.

if OBJECT_ID('tempdb..#Something') is not null
    drop table #Something

CREATE TABLE #Something
(
    Name char(3)
    , Location varchar(50)
    , NameLink varchar(10)
    , LocationLink varchar(50)
    , FinalLocation varchar(50)
    , Material int
)

insert #Something
select 'C50'
    , '2398::3276::3916'
    , 'GA-4-2'
    , '58::52::24'
    , '558::352::324::70'
    , 93530

select * from #Something

select Name
    , LEFT(Location, charindex(':', Location, 0) - 1)
    , PARSENAME(replace(Location, '::', '.'), 3)
    , NameLink
    , PARSENAME(replace(LocationLink, '::', '.'), 3)
    , PARSENAME(replace(FinalLocation, '::', '.'), 4)
    , Material
from #Something

UNION ALL

select Name
    , LEFT(Location, charindex(':', Location, 0) - 1)
    , PARSENAME(replace(Location, '::', '.'), 2)
    , NameLink
    , PARSENAME(replace(LocationLink, '::', '.'), 2)
    , PARSENAME(replace(FinalLocation, '::', '.'), 3)
    , Material
from #Something

UNION ALL

select Name
    , LEFT(Location, charindex(':', Location, 0) - 1)
    , PARSENAME(replace(Location, '::', '.'), 1)
    , NameLink
    , PARSENAME(replace(LocationLink, '::', '.'), 1)
    , PARSENAME(replace(FinalLocation, '::', '.'), 2)
    , Material
from #Something

UNION ALL

select Name
    , LEFT(Location, charindex(':', Location, 0) - 1)
    , PARSENAME(replace(Location, '::', '.'), 4)
    , NameLink
    , PARSENAME(replace(LocationLink, '::', '.'), 4)
    , PARSENAME(replace(FinalLocation, '::', '.'), 1)
    , Material
from #Something