0

I was wondering if there are other methods to split columns or much better methods than these two

I am going to put some code so we can talk the same language

--CREATING TABLE
CREATE TABLE BOOKS(
ID VARCHAR(MAX) NULL
) 
/*
  BOOKS 
  PRODUCTID, NAME, PAGES, WEIGHT, SIZE, TYPE
*/
INSERT INTO BOOKS (ID)
VALUES('B001,INTRODUCTION TO SQL,500,100G,MID,TECH')
      ,('B002,ADVANCED SQL SERVER PRACTICES,200,200G,BIG,TECH')
      ,('B003,SQL SERVER PERFORMANCE,1000,500G,BIG,TECH')
      ,('B004,SQL SERVER MANUAL,50,30G,SMALL,TECH')
          ,('B004,SQL SERVER MANUAL,50,30G,SMALL,TECH')

That will be my demo table, as you can see I have a table with comma separated values

For splitting this values I am going to use pivot combined with a CTE

/*PIVOTING TABLE, ASIGNING A RN TO COLUMNS AND GETTING BACK VALUES*/
WITH C AS(
SELECT ID
      ,value 
      ,ROW_NUMBER() OVER(PARTITION BY ID ORDER BY (SELECT NULL)) as rn
FROM BOOKS BO
    CROSS APPLY STRING_SPLIT(ID, ',') AS BK
)
SELECT ID
      ,[1] AS PRODUCTID
      ,[2] AS NAME
      ,[3] AS PAGES
      ,[4] AS WEIGHT
      ,[5] AS SIZE
      ,[6] AS TYPE
FROM C
PIVOT(
    MAX(VALUE)
    FOR RN IN([1],[2],[3],[4],[5],[6])  
) as PVT

It works fine but in this case the order of strings that it returns is not guaranteed (Ex, 1,2,3,4). column1 = 1, column2 = 3 column3=2 column4 =4, and I am expecting to get 1,2,3,4 The other one is a well known here in stackoverflow by using XML and Nodes

The other one is a well known here in stackoverflow by using XML and Nodes

SELECT DISTINCT
    S.a.value('(/H/r)[1]', 'VARCHAR(100)') AS PRODUCTID
   ,S.a.value('(/H/r)[2]', 'VARCHAR(100)')  AS NAME
   , S.a.value('(/H/r)[3]', 'VARCHAR(100)') AS PAGES
   , S.a.value('(/H/r)[4]', 'VARCHAR(100)') AS WEIGHT
   , S.a.value('(/H/r)[5]', 'VARCHAR(100)') AS SIZE
   , S.a.value('(/H/r)[6]', 'VARCHAR(100)') AS TYPE
FROM
(
SELECT *,CAST (N'<H><r>' + REPLACE(ID, ',', '</r><r>')  
               + '</r></H>' AS XML) AS [vals]
FROM BOOKS) d 
CROSS APPLY d.[vals].nodes('/H/r') S(a) 

Also it works as expected, but don't get me wrong, it is hard to explain and a little confusing if you are not above the beginner level.

What other better ways are there to split columns in sql server, do microsoft implement a new function for this or do you know another method for doing it. ?

9
  • Why are you storing delimited data at all? That data should clearly be 6 separate columns to start with, and so your table BOOKS should have 6 columns, not 1.
    – Thom A
    Oct 16, 2019 at 15:35
  • I had this scenario lots of times when dealing with customer data at job, believe me data is not always structured specially when working doing data analysis Oct 16, 2019 at 15:36
  • See this article sqlservercentral.com/articles/…. It describes a splitter function that also returns column orders Oct 16, 2019 at 15:38
  • 1
    You, should have a look at the improved version of that, @user1443098: delimitedsplit8k_LEAD
    – Thom A
    Oct 16, 2019 at 15:44
  • 1
    That was me, @user1443098, not Alvaro. ;) And yes, Eirikur spoke a lot to Jeff about the function before he published it (with his "blessing"). Those 2 functions are a great example of the community over at SSC, in my opinion.
    – Thom A
    Oct 16, 2019 at 15:50

2 Answers 2

1

Personally, my method would be to treat the value as what it is, a delimited item, and then pivot it using a cross tab. As ordinal position is important, and STRING_SPLIT does not guarentee this, then DelimitedSplit8k_LEAD is a far better option here:

SELECT MAX(CASE DS.ItemNumber WHEN 1 THEN NULLIF(DS.Item,'') END) AS PRODUCTID,
       MAX(CASE DS.ItemNumber WHEN 2 THEN NULLIF(DS.Item,'') END) AS [NAME],
       MAX(CASE DS.ItemNumber WHEN 3 THEN NULLIF(DS.Item,'') END) AS PAGES,
       MAX(CASE DS.ItemNumber WHEN 4 THEN NULLIF(DS.Item,'') END) AS WEIGHT,
       MAX(CASE DS.ItemNumber WHEN 5 THEN NULLIF(DS.Item,'') END) AS SIZE,
       MAX(CASE DS.ItemNumber WHEN 6 THEN NULLIF(DS.Item,'') END) AS [TYPE]
FROM dbo.BOOKS B
     CROSS APPLY dbo.DelimitedSplit8K_LEAD(B.ID,',') DS
GROUP BY B.ID;
1

If 2016+, yet another option is JSON.

JSON seems to outperform XML, especially in Select Fragment and Select Value ( ref )

Example dbFiddle

Select B.* 
 From BOOKS A
 Cross Apply (
               Select Pos1= JSON_VALUE(J,'$[0]')
                     ,Pos2= JSON_VALUE(J,'$[1]')
                     ,Pos3= JSON_VALUE(J,'$[2]')
                     ,Pos4= JSON_VALUE(J,'$[3]')
                     ,Pos5= JSON_VALUE(J,'$[4]')
                     ,Pos6= JSON_VALUE(J,'$[5]')
                From (values ('["'+replace(replace(ID,'"','\"'),',','","')+'"]'))A(J)
             ) B
17
  • Have you benched it agains sqlservercentral.com/articles/…? Oct 16, 2019 at 17:28
  • @user1443098 I don't think I'd have to. As impressive as Larnu's function is, it is still a table-valued function and aggregation vs a native function. Oct 16, 2019 at 17:32
  • Well IIRC (though memory is tricky!) I think Jeff's benchmarks showed that is not always the case. Oct 16, 2019 at 17:34
  • Personally, on my Home Workstation (i7 8700 32GB RAM), with 630 rows I found DelimitedSplit8K_LEAD to take 10ms, where as the JSON solution on average 16ms. At 3130: 48~ vs 83~. Oddly, at 15000~ rows they were on par, and then at 80,000~ rows JSON was much slower (1000ms~ vs 2000ms~). At 400000~ rows, JSON was seconds slower. Native functions aren't always better. look at the awful FORMAT function, for example. :)
    – Thom A
    Oct 16, 2019 at 17:53
  • 1
    @Larnu The FORMAT function was a cheap shot :) Oct 16, 2019 at 17:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.