I have a CommentsTable table with columns like CommentA, CommentB, CommentC, CommentD, CommentE .
All comment columns are VARCHAR (200) , by default all columns are also NULL .
The data looks like this:
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 to avoid null values ββand the remaining values ββare the same as comma .
So, the expected result, for example:
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 with a simple request:
SELECT CommentId, ISNULL(CommentA, '') + ', ' + ISNULL(CommentB, '') + ', ' + ISNULL(CommentC, '') + ', ' + ISNULL(CommentD, '') + ', ' + ISNULL(CommentE, '') [CommentDetails] FROM CommentsTable WHERE ......
But there are unwanted comma , so IIF added
SELECT CommentId, IIF(ISNULL(CommentA, '') <> '', (CommentA + ', '), '') + IIF(ISNULL(CommentB, '') <> '', (CommentB + ', '), '') + IIF(ISNULL(CommentC, '') <> '', (CommentC + ', '), '') + IIF(ISNULL(CommentD, '') <> '', (CommentD + ', '), '') + ISNULL(CommentE, '') [CommentDetails] FROM CommentsTable WHERE ......
But here also, comma happened in the last position for some cases (If CommentD, CommetE - NULL .
Is there a way to reach a solution for all cases.
Sample SQL Fiddle