在SQL Server中,可以使用以下方法来模拟类似于Oracle中的WM_CONCAT函数的功能:
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;
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;
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;