以下是我的代码。
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.'
正在产生输出: -
Attachments, A, B, C, D are missing.
我怎样才能避免在#34; Attachments
"之后的第一个逗号。 ?请帮忙。
也欢迎满足要求的其他技术。
感谢。
答案 0 :(得分:5)
而不是使用undocumented/unsupported way of concatenating strings,而是使用FOR XML PATH
:
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.'
答案 1 :(得分:3)
试试这个:
SELECT @msg = ISNULL(@msg + ', ', 'Attachements ') + Message FROM CTE
并查看FOR XML
方法来连接字符串
答案 2 :(得分:1)
用例
SELECT @msg = case when @msg is NULL then 'Attachment '
else
COALESCE(@msg + ', ','')
end
+ Message FROM CTE
SELECT @msg + ' are missing.'
答案 3 :(得分:0)
只需更改最后两行
SELECT @msg = COALESCE(@Msg + ', ','') + Message FROM CTE
SELECT 'Attachments '+@msg + ' are missing.'