在sql Server 2008上,我试图将所有选定值的逗号分隔列表添加到变量中.
SELECT field FROM table
收益:
+-------+ | field | +-------+ | foo | +-------+ | bar | +-------+
我想得到:
“foo,bar,”
我试过了:
DECLARE @foo NVARCHAR(MAX) SET @foo = '' SELECT @foo = @foo + field + ',' FROM TABLE PRINT @foo
什么都不返回.我究竟做错了什么?
解决方法
您需要更改NULL
SELECT @foo = @foo + ISNULL(field + ',','') FROM TABLE
或删除它们
SELECT @foo = @foo + field + ',' FROM TABLE WHERE field IS NOT NULL