Click here to Skip to main content
15,889,838 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
Quote:
I have a table like the following:

SQL
SongsName	PlstID
a,b,c,d,e	166
a,d,e,f,g	165


Quote:
I want output like

SQL
SongsName	PlstID
a		166
b		166
c		166
d		166
e		166
a		165
d		165
e		165
f		165
g		165
Posted

Hi,

try following code block..

SQL
WITH SplitCTE AS (
SELECT CAST('' + REPLACE(SongName, ',', '') + '' AS XML) AS Songs,PlstID
FROM YourTableName
)
-- Xquery to get the desired result set using CROSS JOIN
SELECT x.i.value('.', 'VARCHAR(MAX)') AS SongName,PlstID
FROM SplitCTE CROSS APPLY Songs.nodes('//i') x(i)


Thank you..

Happy coding :)
 
Share this answer
 
Hi,

Try like this
SQL
SELECT T.value 'SongsName', M.PlstID
FROM yourTable M
INNER JOIN (SLECT value FROM dbo.splitFunction (M.SongsName,',')) T ON 1=1
-- User Define Function (dbo.splitFunction)

Regards,
GVPrabu
 
Share this answer
 
v2
Try this:
SQL
DECLARE @tmp TABLE (SongsName VARCHAR(300), PlstID INT)

INSERT INTO @tmp (SongsName, PlstID)
VALUES('a,b,c,d,e', 166)
INSERT INTO @tmp (SongsName, PlstID)
VALUES('a,d,e,f,g', 165)

;WITH CTESongs AS
(
	SELECT PlstID, LEFT(SongsName, CHARINDEX(',',SongsName)-1) AS Song, RIGHT(SongsName, LEN(SongsName) - CHARINDEX(',',SongsName)) AS Remainder
	FROM @tmp
	WHERE CHARINDEX(',',SongsName)>0
	UNION ALL
	SELECT PlstID, LEFT(Remainder, CHARINDEX(',',Remainder)-1) AS Song, RIGHT(Remainder, LEN(Remainder) - CHARINDEX(',',Remainder)) AS Remainder
	FROM CTESongs
	WHERE CHARINDEX(',',Remainder)>0
	UNION ALL
	SELECT PlstID, Remainder AS Song, NULL AS Remainder
	FROM CTESongs
	WHERE CHARINDEX(',',Remainder)=0
)
SELECT *
FROM CTESongs
--ORDER BY PlstID, Song


Have a look here: WITH Common table expression[^]
 
Share this answer
 
We have the best example to solve the comma separated value of field in sql server

declare @String as varchar(max)
declare @Delimiter as char(1)
declare @str as varchar(max)
declare @s as varchar(max)
declare @charIndex as int
declare @b as int

set @Delimiter = ',';
set @string = a(01:00:00),b(02:00:00),c(03:00:00),d(04:00:00);

create table #temptable(Items varchar(max))

declare @idx int
declare @slice varchar(8000)

select @idx = 1
if len(@String)<1 or @String is null return

while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String

if(len(@slice)>0)


set @charIndex = CHARINDEX('(',@slice)
set @str = SUBSTRING(@slice,0,@charIndex)

insert into #temptable(Items) values(@str)

set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end

select * from #temptable

drop table #temptable
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900