是否可以将多个结果合并到SQL Server中的单个字符串中?
我有下表:
NameID Name
------ -----
1 Alvin
2 Alan
3 Ben
4 Tom
如何选择表格并返回选择结果,如下所示:
Group
-----
Alvin, Alan, Ben and Tom
答案 0 :(得分:1)
以下是使用HEADER EXPDTA REMARK HETNAM FORMUL
OXIDOREDUCTASE 2LU5 SOLID-STATE NMR RESOLUTION. NOT APPLICABLE. COPPER (II) ION (here better to say last column because certain diversity exists before "copper") CU 2+
ZN ZINC ZN 2+
FOR XML PATH
SELECT Stuff((SELECT ', ' + NAME
FROM Yourtable
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
方法可帮助我们避免在结果中对value
保留字符进行编码
答案 1 :(得分:0)
试试这个:
SELECT
SUBSTRING((SELECT
',' + CAST(Name AS varchar)
FROM table_name
FOR xml PATH (''))
, 2, 10000) AS Group1
答案 2 :(得分:0)
试试这个:
DECLARE @a TABLE
(Col1 int,
Col2 varchar(5)
);
--
DECLARE @b VARCHAR(500) = '';
--
INSERT INTO @a (Col1, Col2)
VALUES (1,'Alvin'),
(2,'Alan'),
(3,'Ben'),
(4,'Tom');
--
SELECT @b = COALESCE(@b,'') + Col2 + ', '
FROM @a;
--
SELECT STUFF(STUFF(@b, LEN(@b), 1, ''), LEN(@b) + 1 - CHARINDEX(',', REVERSE(STUFF(@b, LEN(@b), 1, ''))), 1, ' and')
输出:
阿尔文,艾伦,本和汤姆