阅读量:0
在SQL Server中,可以使用以下方法来模拟类似于Oracle中的WM_CONCAT函数的功能:
- 使用XML PATH
SELECT ID, STUFF((SELECT ', ' + ColumnName FROM TableName t2 WHERE t1.ID = t2.ID FOR XML PATH('')), 1, 2, '') AS ConcatenatedColumn FROM TableName t1 GROUP BY ID;
- 使用FOR XML PATH(‘’)和STUFF函数结合
SELECT ID, STUFF((SELECT ', ' + ColumnName FROM TableName t2 WHERE t1.ID = t2.ID FOR XML PATH('')), 1, 2, '') AS ConcatenatedColumn FROM TableName t1 GROUP BY ID;
- 使用自定义函数 可以创建一个自定义函数来模拟WM_CONCAT函数的功能,例如:
CREATE FUNCTION dbo.WM_Concat ( @ID INT ) RETURNS VARCHAR(MAX) AS BEGIN DECLARE @ConcatenatedColumn VARCHAR(MAX) SELECT @ConcatenatedColumn = COALESCE(@ConcatenatedColumn + ', ', '') + ColumnName FROM TableName WHERE ID = @ID RETURN @ConcatenatedColumn END
然后可以使用该函数来实现类似WM_CONCAT函数的功能:
SELECT ID, dbo.WM_Concat(ID) AS ConcatenatedColumn FROM TableName GROUP BY ID;