在Oracle中,由于WM_CONCAT函數在12c版本之后被棄用,可以使用以下替代方法:
LISTAGG函數:LISTAGG函數可以用來實現類似WM_CONCAT的功能,可以將指定列的值連接成一個字符串,語法如下:
SELECT department_id, LISTAGG(employee_name, ', ') WITHIN GROUP (ORDER BY employee_name) AS employees
FROM employees
GROUP BY department_id;
XMLAGG函數:XMLAGG函數可以將查詢結果轉換為XML格式,并且可以使用XML序列函數來實現字符串連接,語法如下:
SELECT department_id, RTRIM(XMLAGG(XMLELEMENT(e, employee_name || ', ')).EXTRACT('//text()'), ', ') AS employees
FROM employees
GROUP BY department_id;
自定義函數:可以編寫一個自定義的函數來實現字符串連接的功能,例如使用PL/SQL語言編寫一個函數來實現:
CREATE OR REPLACE FUNCTION concat_values (p_cursor SYS_REFCURSOR)
RETURN VARCHAR2
IS
v_result VARCHAR2(4000);
v_value VARCHAR2(4000);
BEGIN
LOOP
FETCH p_cursor INTO v_value;
EXIT WHEN p_cursor%NOTFOUND;
v_result := v_result || ', ' || v_value;
END LOOP;
RETURN LTRIM(v_result, ', ');
END concat_values;
使用示例:
DECLARE
v_result VARCHAR2(4000);
BEGIN
OPEN employees_cursor FOR
SELECT employee_name
FROM employees
WHERE department_id = 10;
v_result := concat_values(employees_cursor);
CLOSE employees_cursor;
DBMS_OUTPUT.PUT_LINE(v_result);
END;