PIPIONE
这个测试场景将说明这一点。创建临时表:CREATE table #temp (EmpId INT, EmpName VARCHAR(100));WITH N(N)AS (SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1))M(N))
,tally(N)AS(SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a,N b,N c,N d,N e,N f)INSERT #tempSELECT EmpId, EmpName FROM (values(1, 'M
ary'),(1, 'John'),(1, 'Sam')) x(EmpId, EmpName)CROSS APPLY (SELECT top 2000 N FROM tally) yUNION ALLSELECT EmpId, EmpName FROM (valu
es(2, 'Alaina'),(2, 'Edward')) x(EmpId, EmpName)CROSS APPLY(SELECT top 2000 N FROM tally) y这只有10.000行。但很多相同的空白处。Oleg的答案中的这个查询在我的数据库上花费了64秒。SELECT distinct
EmpId,
(
SELECT EmpName+','
FROM #temp t2 WHERE t2.EmpId = t1.EmpId FOR XML PATH('')
) ConcatenatedFROM #temp t1在这种情况下,区分不是清理行的正确方法。为了避免这个笛卡儿连接,在像这样加入之前减少ID的初始数量。这是正确的处理方法:;WITH CTE as(
SELECT distinct EmpId FROM #temp)SELECT
EmpId,
STUFF((
SELECT ','+EmpName FROM #temp t2 WHERE t2.EmpId = t1.EmpId FOR XML PATH('')
), 1,1,'') ConcatenatedFROM CTE t1这需要不到1秒