sql - Multiple column values into a single column as comma separated value -
i have table commentstable columns like, commenta, commentb, commentc, commentd, commente.
all comments columns varchar (200), default columns null also.
the data looks like:
commentid commenta commentb commentc commentd commente --------------------------------------------------------------------- 12345 null c 001 c 002 null c 003 45678 c 005 null null c 007 null 67890 c 010 null c 011 c 012 null 36912 c 021 c 023 c 024 c 025 c 026 i need avoid null values , remaining values concatenate comma.
so, expected output like:
commentid commetdetails ------------------------------- 12345 c 001, c 002, c 003 45678 c 005, c 007 67890 c 010, c 011, c 012 36912 c 021, c 023, c 024, c 025, c 026 i tried simple query:
select commentid, isnull(commenta, '') + ', ' + isnull(commentb, '') + ', ' + isnull(commentc, '') + ', ' + isnull(commentd, '') + ', ' + isnull(commente, '') [commentdetails] commentstable ...... --some conditions but unwanted comma occurred, added iif
select commentid, iif(isnull(commenta, '') <> '', (commenta + ', '), '') + iif(isnull(commentb, '') <> '', (commentb + ', '), '') + iif(isnull(commentc, '') <> '', (commentc + ', '), '') + iif(isnull(commentd, '') <> '', (commentd + ', '), '') + isnull(commente, '') [commentdetails] commentstable ...... --some conditions but here also, comma occurred in last position cases (if commentd, commete null.
is there way achieve solve cases.
you can use isnull isnull(',' + commenta, '') , write query this.
select commentid, stuff( isnull(',' + commenta, '') + isnull(',' + commentb, '') + isnull(',' + commentc, '') + isnull(',' + commentd, '') + isnull(',' + commente, ''),1,1,'') [commentdetails] commentstable ...... //some conditions see result in sql fiddle.
Comments
Post a Comment