在Oracle中,您可以使用用戶自定義聚合函數(User-Defined Aggregate Functions,UDAF)來實現類似于WM_CONCAT的功能
CREATE OR REPLACE TYPE my_wm_concat_type AS OBJECT (
concatenated_string VARCHAR2(32767),
STATIC FUNCTION ODCIAggregateInitialize(sctx IN OUT my_wm_concat_type) RETURN NUMBER,
MEMBER FUNCTION ODCIAggregateIterate(self IN OUT my_wm_concat_type, value IN VARCHAR2) RETURN NUMBER,
MEMBER FUNCTION ODCIAggregateTerminate(self IN my_wm_concat_type, returnValue OUT VARCHAR2, flags IN NUMBER) RETURN NUMBER,
MEMBER FUNCTION ODCIAggregateMerge(self IN OUT my_wm_concat_type, sctx2 IN my_wm_concat_type) RETURN NUMBER
);
/
CREATE OR REPLACE TYPE BODY my_wm_concat_type IS
STATIC FUNCTION ODCIAggregateInitialize(sctx IN OUT my_wm_concat_type) RETURN NUMBER IS
BEGIN
sctx := my_wm_concat_type(NULL);
RETURN ODCIConst.Success;
END;
MEMBER FUNCTION ODCIAggregateIterate(self IN OUT my_wm_concat_type, value IN VARCHAR2) RETURN NUMBER IS
BEGIN
IF self.concatenated_string IS NULL THEN
self.concatenated_string := value;
ELSE
self.concatenated_string := self.concatenated_string || ',' || value;
END IF;
RETURN ODCIConst.Success;
END;
MEMBER FUNCTION ODCIAggregateTerminate(self IN my_wm_concat_type, returnValue OUT VARCHAR2, flags IN NUMBER) RETURN NUMBER IS
BEGIN
returnValue := self.concatenated_string;
RETURN ODCIConst.Success;
END;
MEMBER FUNCTION ODCIAggregateMerge(self IN OUT my_wm_concat_type, sctx2 IN my_wm_concat_type) RETURN NUMBER IS
BEGIN
IF sctx2.concatenated_string IS NOT NULL THEN
IF self.concatenated_string IS NULL THEN
self.concatenated_string := sctx2.concatenated_string;
ELSE
self.concatenated_string := self.concatenated_string || ',' || sctx2.concatenated_string;
END IF;
END IF;
RETURN ODCIConst.Success;
END;
END;
/
CREATE OR REPLACE FUNCTION my_wm_concat(input VARCHAR2) RETURN VARCHAR2
PARALLEL_ENABLE AGGREGATE USING my_wm_concat_type;
/
現在您可以在SQL查詢中像使用WM_CONCAT一樣使用MY_WM_CONCAT函數:
SELECT deptno, MY_WM_CONCAT(ename)
FROM emp
GROUP BY deptno;
請注意,這個實現是簡單的,并沒有處理所有WM_CONCAT的特性,例如排序、分隔符等。您可以根據需要對聚合類型進行修改以實現更多功能。