3

Below is my code.

DECLARE @msg NVARCHAR(MAX) = NULL

;WITH CTE AS (
                    SELECT 'A' AS Message
                UNION
                    SELECT 'B' AS Message
                UNION
                    SELECT 'C' AS Message
                UNION
                    SELECT 'D' AS Message
)

SELECT @msg = COALESCE(ISNULL(@msg,'Attachements') + ', ','') +  Message FROM CTE

SELECT @msg + ' are missing.'

It is generating output :-

Attachments, A, B, C, D are missing.

How can I avoid first comma after word "Attachments" ? Please help.

Other techniques to satisfy the requirement would also be welcome.

Thanks.

Aditya
  • 2,299
  • 5
  • 32
  • 54

4 Answers4

5

Instead of using the undocumented/unsupported way of concatenating strings, use FOR XML PATH instead:

DECLARE @msg NVARCHAR(MAX) = NULL

;WITH CTE AS (
    SELECT 'A' AS Message
    UNION
    SELECT 'B' AS Message
    UNION
    SELECT 'C' AS Message
    UNION
    SELECT 'D' AS Message
)

SELECT @msg = 'Attachments ' + 
    STUFF((
        SELECT ', ' + Message 
        FROM CTE
        ORDER BY Message
        FOR XML PATH(''), TYPE).value('.[1]', 'NVARCHAR(MAX)')
    , 1, 2, ' ')

SELECT @msg + ' are missing.'
Community
  • 1
  • 1
Felix Pamittan
  • 31,544
  • 7
  • 41
  • 67
  • Will go with this one considering performance. Though I dint understood it enough :( +1 – Aditya Feb 24 '16 at 06:46
  • And for what " TYPE).value('.[1]', 'NVARCHAR(MAX)') " is there ? Strange, I dint used data type in select code !! – Aditya Feb 24 '16 at 09:40
3

Try this:

SELECT @msg = ISNULL(@msg + ', ', 'Attachements ') +  Message FROM CTE

and check out FOR XML approach for concatenating string

Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39
1

use case when

SELECT @msg = case when @msg is NULL then 'Attachment ' 
else
COALESCE(@msg + ', ','') 
end
+ Message FROM CTE
SELECT @msg + ' are missing.'
LKW
  • 180
  • 1
  • 3
  • 13
0

Just change the last two lines

SELECT @msg = COALESCE(@Msg + ', ','') +  Message FROM CTE

SELECT 'Attachments '+@msg + ' are missing.'
mindbdev
  • 404
  • 3
  • 8