在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;