Wrap the fields in ISNULL()
Select TOP 1000 col1,
LTRIM(RTRIM(cast(ISNULL(col2,'') as varchar)))
+ SPACE(2) + '|' + SPACE(2) + LTRIM(RTRIM(cast(ISNULL(col3,'') as varchar)))
+ SPACE(2) + '|' + SPACE(2) + LTRIM(RTRIM(cast(ISNULL(col4,'') as varchar)))
+ SPACE(2) + '|' + SPACE(2) + LTRIM(RTRIM(cast(ISNULL(col5,'') as varchar)))
+ SPACE(2) + '|' + SPACE(2) + LTRIM(RTRIM(cast(ISNULL(col6,'') as varchar))))
from mytable
Or COALESCE()
Select TOP 1000 col1,
LTRIM(RTRIM(cast(COALESCE(col2,'') as varchar)))
+ SPACE(2) + '|' + SPACE(2) + LTRIM(RTRIM(cast(COALESCE(col3,'') as varchar)))
+ SPACE(2) + '|' + SPACE(2) + LTRIM(RTRIM(cast(COALESCE(col4,'') as varchar)))
+ SPACE(2) + '|' + SPACE(2) + LTRIM(RTRIM(cast(COALESCE(col5,'') as varchar)))
+ SPACE(2) + '|' + SPACE(2) + LTRIM(RTRIM(cast(COALESCE(col6,'') as varchar))))
from mytable
If using SQL Server 2012 it's even easier thanks to CONCAT()
(you can replace SPACE(2)
with ' | '
above too):
Select TOP 1000 col1
,CONCAT(LTRIM(RTRIM(cast(col2 as varchar)))
,' | ', LTRIM(RTRIM(col3))
,' | ', LTRIM(RTRIM(col4))
,' | ', LTRIM(RTRIM(col5))
,' | ', LTRIM(RTRIM(col6)))
from mytable