Thursday, 21 November 2013

Split column value using sql

CREATE TABLE split_sample (
 Employee_no INT identity(1, 1)
 ,Project_code VARCHAR(50)
 )

INSERT INTO split_sample (Project_code)
VALUES ('2001,2003,2004')
 ,('')
 ,('2001')
 ,('2001,2002')
 ,('2002,2003,2004')
SELECT * FROM split_sample 





WITH cte_table AS (
  SELECT Employee_no
   ,cast(CASE 
     WHEN charindex(',', Project_code) > 0
      THEN SUBSTRING(Project_code, 1, charindex(',', Project_code) - 1)
     ELSE Project_code
     END AS VARCHAR(50)) Project_code
   ,CASE 
    WHEN charindex(',', Project_code) > 0
     THEN stuff(Project_code, 1, charindex(',', Project_code), '')
    ELSE ''
    END AS cte_str
  FROM split_sample
  
  UNION ALL
  
  SELECT Employee_no
   ,cast(CASE 
     WHEN charindex(',', cte_str) > 0
      THEN SUBSTRING(cte_str, 1, charindex(',', cte_str) - 1)
     ELSE cte_str
     END AS VARCHAR(50)) cte_str
   ,CASE 
    WHEN charindex(',', cte_str) > 0
     THEN stuff(cte_str, 1, charindex(',', cte_str), '')
    ELSE ''
    END AS cte_str
  FROM cte_table
  WHERE cte_str <> ''
  )

SELECT Employee_no
 ,Project_code
FROM cte_table

No comments:

Post a Comment