How to convert comma separated value into rows in

2019-09-20 16:29发布

问题:

How can I convert comma separated value as :

Table

User Name  Unit
ABC        2,3  

to the following :

User Name  Unit
ABC        2  
ABC        3

回答1:

You have tagged your question with SQL Server 2016, in SQL Server 2016 there is a new function STRING_SPLIT.

In SQL Server 2016 your query should be as simple as:

declare @tab table ([user_name] varchar(10),Unit varchar(100))
insert into @tab
VALUES ('ABC','1,2')

SELECT t.[user_name]
       , Value as Unit
FROM @tab t 
    CROSS APPLY STRING_SPLIT(t.Unit , ',') 


回答2:

In SQL server below will be the logic Hope it helps

declare @tab table ([user_name] varchar(10),val varchar(100))
insert into @tab
select 'ABC','1,2'

SELECT A.[user_name],  
     Split.a.value('.', 'VARCHAR(100)') AS String  
 FROM  (SELECT [user_name],  
         CAST ('<M>' + REPLACE(val, ',', '</M><M>') + '</M>' AS XML) AS String  
     FROM  @tab) AS A CROSS APPLY String.nodes ('/M') AS Split(a); 

output

user_name   String
ABC          1
ABC          2


回答3:

You can use the fn_split function.



回答4:

CREATE FUNCTION dbo.SplitCSVs (@CSVString varchar(1000))

RETURNS @SeparatedValues TABLE (Value VARCHAR(100))
AS
BEGIN
 DECLARE @CommaPosition INT
 WHILE (CHARINDEX(',', @CSVString, 0) > 0)
 BEGIN
  SET @CommaPosition = CHARINDEX(',', @CSVString, 0)
  INSERT INTO @SeparatedValues (Value)
  SELECT SUBSTRING(@CSVString, 0, @CommaPosition)
  SET @CSVString = STUFF(@CSVString, 1, @CommaPosition, '')
 END
  INSERT INTO @SeparatedValues (Value)
  SELECT @CSVString

 RETURN
END

SELECT * FROM dbo.SplitCSVs('aby,123')