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
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
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 , ',')
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
You can use the fn_split
function.
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')