2

I have data currently in my table like below under currently section. I need the selected column data which is comma delimited to be converted into the format marked in green (Read and write of a category together) enter image description here

Any ways to do it in SQL Server?

Please do look at the proposal data carefully.... Maybe I wasn't clear before: this isn't merely the splitting that is the issue but to group all reads and writes of a category together(sometimes they are just merely reads/writes), it's not merely putting comma separated values in multiple rows.

--    script:
    use master 
    Create table prodLines(id int  , prodlines varchar(1000))
    --drop table prodLines
    insert into prodLines values(1, 'Automotive Coatings (Read), Automotive Coatings (Write), Industrial Coatings (Read), S.P.S. (Read), Shared PL''s (Read)')
    insert into prodLines values(2, 'Automotive Coatings (Read), Automotive Coatings (Write), Industrial Coatings (Read), S.P.S. (Read), Shared PL''s (Read)')

    select * from prodLines
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
MR K
  • 113
  • 1
  • 1
  • 12
  • did you try to search for it ? there are many many such example ever ask in SO . https://www.google.com.sg/#q=split+csv+string+to+rows+in+sql+server – Squirrel Apr 12 '16 at 06:44
  • Instead of posting an image, post a consumable create and insert script for us to work with. – Felix Pamittan Apr 12 '16 at 06:51
  • See my edits , i have tried to explain , why it isnt the same – MR K Apr 12 '16 at 06:52
  • 1
    basically still the same. Use a csv splitter to split into multiple rows and then you concatenate back based on your rules of "same category". – Squirrel Apr 12 '16 at 07:02
  • [Split strings the right way](http://sqlperformance.com/2012/07/t-sql-queries/split-strings) – Zohar Peled Apr 12 '16 at 07:12

3 Answers3

2

Take a look at STRING_SPLIT, You can do something like:

SELECT user_access
FROM Product
CROSS APPLY STRING_SPLIT(user_access, ',');

or what ever you care about.

Wajih
  • 4,227
  • 2
  • 25
  • 40
2

Using Jeff's DelimitedSplit8K

; 
with cte as
(
    select  id, prodlines, ItemNumber, Item = ltrim(Item),
        grp = dense_rank() over (partition by id order by replace(replace(ltrim(Item), '(Read)', ''), '(Write)', ''))
    from    #prodLines pl
        cross apply dbo.DelimitedSplit8K(prodlines, ',') c
)
select  id, prodlines, prod = stuff(prod, 1, 1, '')
from    cte c
    cross apply
    (
        select  ',' + Item
        from    cte x
        where   x.id    = c.id
        and x.grp   = c.grp
        order by x.Item
        for xml path('')
    ) i (prod)
Squirrel
  • 23,507
  • 4
  • 34
  • 32
0

Simply use LATERAL VIEW EXPLODE function:

select access  from Product
LATERAL VIEW explode(split(user_access, '[,]')) usrAccTable AS access;
Reihan_amn
  • 2,645
  • 2
  • 21
  • 21