How to convert comma separated value into rows in

2019-09-20 16:34发布

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

4条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-20 17:18

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 , ',') 
查看更多
啃猪蹄的小仙女
3楼-- · 2019-09-20 17:22

You can use the fn_split function.

查看更多
聊天终结者
4楼-- · 2019-09-20 17:25
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')
查看更多
趁早两清
5楼-- · 2019-09-20 17:34

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
查看更多
登录 后发表回答