此查询返回我想要的内容(查询中的逗号分隔值)
SELECT emp_id, LISTAGG(HOBBIES, ',') WITHIN GROUP (ORDER BY HOBBIES)
FROM employee_list
WHERE emp_id = 123456
GROUP BY emp_id;
结果:
Squash,Tennis,Walking
初始数据:
emp_id hobbies
-------------------
123456 Walking
123456 Tennis
123456 Squash
000001 Bowling
000002 Tennis
000002 Soccer
当我尝试将其转换为这样的存储过程时:
CREATE OR REPLACE PROCEDURE GET_EMP_ID_FOR_HOBBIES(id NUMBER)
AS
x varchar(255);
BEGIN
SELECT emp_id, LISTAGG(HOBBIES, ',') WITHIN GROUP (ORDER BY HOBBIES)
INTO x
FROM employee_list
WHERE emp_id = id
GROUP BY HOBBIES;
END;
在编译时返回以下错误
错误(6,8):PL / SQL:ORA-00947:值不足
如果是插入内容,我会理解的。我做错了什么?
答案 0 :(得分:1)
您要选择两个列表达式emp_id
和listagg()
的结果-但您只选择一个变量x
。
您需要两个变量,并在into
子句中列出两者,以匹配列表达式。
...
AS
l_emp_id employee_list.emp_id%TYPE;
l_hobbies varchar2(4000); -- has to be big enough
BEGIN
SELECT emp_id, LISTAGG(HOBBIES, ',') WITHIN GROUP (ORDER BY HOBBIES)
INTO l_emp_id, l_hobbies
FROM employee_list
WHERE emp_id = id
GROUP BY emp_id;
...
如果您确实确实想要一个变量,那么就需要一个列表达式-删除其中一个,因为您实际上并不需要ID的另一个副本:
...
AS
l_hobbies varchar2(4000); -- has to be big enough
BEGIN
SELECT LISTAGG(HOBBIES, ',') WITHIN GROUP (ORDER BY HOBBIES)
INTO l_hobbies
FROM ...
或不太可能将ID和爱好连接成单个字符串值。当然,x
变量必须足够大以容纳组合的字符串。
将值包含在局部变量中后,这取决于您打算如何处理这些值。