I want to concatenate multiple columns, separated by ;, in MS-SQL Server 2008.
The problem that I have is that without the CONCAT() I don't know how to handle NULL columns and not have results like this tattoos;comics;;;
Here you have the script to create the sample data:
declare @tbl as table (
id int
,kw1 varchar(15)
,kw2 varchar(15)
,kw3 varchar(15)
,kw4 varchar(15)
,kw5 varchar(15)
);
insert into @tbl values
(1, 'innocence', 'graphic novel', 'cartoon', NULL, 'comics')
,(2, 'tattoos', 'comics', NULL, NULL, NULL)
,(3, NULL, 'music', 'cartoon', 'adventure', 'film')
And the table:
+----+-----------+---------------+---------+-----------+--------+
| id | kw1 | kw2 | kw3 | kw4 | kw5 |
+----+-----------+---------------+---------+-----------+--------+
| 1 | innocence | graphic novel | cartoon | NULL | comics |
| 2 | tattoos | comics | NULL | NULL | NULL |
| 3 | NULL | music | cartoon | adventure | film |
+----+-----------+---------------+---------+-----------+--------+
So my actual result is this:
+----+-----------------------------------------+
| id | Keywords |
+----+-----------------------------------------+
| 1 | innocence;graphic novel;cartoon;;comics |
| 2 | tattoos;comics;;; |
| 3 | ;music;cartoon;adventure;film |
+----+-----------------------------------------+
But this is what i want:
+----+----------------------------------------+
| id | Keywords |
+----+----------------------------------------+
| 1 | innocence;graphic novel;cartoon;comics |
| 2 | tattoos;comics |
| 3 | music;cartoon;adventure;film |
+----+----------------------------------------+
Query:
SET CONCAT_NULL_YIELDS_NULL OFF;
select
id
,kw1 + ';' + kw2 + ';' + kw3 + ';' + kw4 + ';' + kw5 as Keywords
FROM @tbl
Any help is appreciated!
+, but i edited my question+, anullvalue in any column will result in anull, not in;;