以下代码返回一个字段,一个字符串,根据输入显示“28”。
SELECT data.id, LTRIM(SYS_CONNECT_BY_PATH(name, ', '),',') conc_names
FROM (
SELECT id, name, ROW_NUMBER() OVER (order by name) rownumber, COUNT(*) OVER () cnt
FROM (
SELECT es.EVENT_ID as id, s.SERVICE_NAME as name FROM DT_SERVICES s
JOIN DT_EVENT_SERVICE es ON s.SERVICE_ID = es.SERVICE_ID
WHERE es.EVENT_ID = 28
)
) data
WHERE rownumber = cnt
START WITH rownumber = 1
CONNECT BY PRIOR rownumber = rownumber-1;
如何创建一个SQL函数,以便我可以传入任何数字(而不是28),函数将返回该选择的结果是什么?
我尝试创建一个,但我不断收到编译错误。
创建函数的当前SQL
create or replace function "DT_SERVICE_STRING" (id in VARCHAR2)
return VARCHAR2 is
begin
DECLARE
result VARCHAR(200);
SELECT data.id, LTRIM(SYS_CONNECT_BY_PATH(name, ', '),',') conc_names
INTO result
FROM (
SELECT id, name, ROW_NUMBER() OVER (order by name) rownumber, COUNT(*) OVER () cnt
FROM (
SELECT es.EVENT_ID as id, s.SERVICE_NAME as name FROM DT_SERVICES s
JOIN DT_EVENT_SERVICE es ON s.SERVICE_ID = es.SERVICE_ID
WHERE es.EVENT_ID = id
)
) data
WHERE rownumber = cnt
START WITH rownumber = 1
CONNECT BY PRIOR rownumber = rownumber-1;
return result;
end;
错误:
编译失败,第7行(15:22:21)
PLS-00103:遇到以下其中一项时遇到符号“SELECT”:begin function pragma procedure子类型当前游标删除存在
答案 0 :(得分:4)
假设你想要一个可以从SQL语句调用的PL / SQL函数(你不能在SQL中定义一个函数),听起来你想要像
这样的东西CREATE OR REPLACE FUNCTION get_conc_names( p_event_id IN dt_event_service.event_id%type )
RETURN VARCHAR2
IS
l_conc_names VARCHAR2(32676);
-- You may want a smaller variable if you know the result will be smaller
BEGIN
SELECT LTRIM(SYS_CONNECT_BY_PATH(name, ', '),',') conc_names
INTO l_conc_names
FROM (
SELECT id, name, ROW_NUMBER() OVER (order by name) rownumber, COUNT(*) OVER () cnt
FROM (SELECT es.EVENT_ID as id, s.SERVICE_NAME as name
FROM DT_SERVICES s
JOIN DT_EVENT_SERVICE es ON s.SERVICE_ID = es.SERVICE_ID
WHERE es.EVENT_ID = p_event_id )
) data
WHERE rownumber = cnt
START WITH rownumber = 1
CONNECT BY PRIOR rownumber = rownumber-1;
RETURN l_conc_names;
END;
根据您刚刚发布的代码,您似乎只需要摆脱DECLARE
并在result
之前和之后移动局部变量BEGIN
的声明IS
。
答案 1 :(得分:0)
我认为分析函数需要在内部内联视图中,然后外部内联视图可以选择它们 - 这就是我总是这样做的。试试这个:
CREATE OR REPLACE FUNCTION get_conc_names( p_event_id IN dt_event_service.event_id%type )
RETURN VARCHAR2
IS
l_conc_names VARCHAR2(32676);
-- You may want a smaller variable if you know the result will be smaller
BEGIN
SELECT LTRIM(SYS_CONNECT_BY_PATH(name, ', '),',') conc_names
INTO l_conc_names
FROM (
SELECT id, name, rownumber, cnt
FROM (SELECT es.EVENT_ID as id
,s.SERVICE_NAME as name
,ROW_NUMBER() OVER (order by name) as rownumber
,COUNT(*) OVER () as cnt
FROM DT_SERVICES s
JOIN DT_EVENT_SERVICE es ON s.SERVICE_ID = es.SERVICE_ID
WHERE es.EVENT_ID = p_event_id )
) data
WHERE rownumber = cnt
START WITH rownumber = 1
CONNECT BY PRIOR rownumber = rownumber-1;
RETURN l_conc_names;
END;