我不確定爲什麼你打擾with
條款,沒有CTE就更簡單;你只需要確定哪些表city
列是:
function myfunc(p_city IN VARCHAR2,
p_order IN VARCHAR2)
RETURN SYS_REFCURSOR IS
v_result SYS_REFCURSOR;
begin
OPEN v_result FOR
'select * from tableA ta
inner join tableB tb on tb.some_col = ta.some_col
where :p_city is null or LOWER(ta.city) like ''%''||:p_city||''%''
order by ' || p_order || ' asc'
using p_city, p_city;
return v_result;
end myfunc;
/
我已經猜到了議席,只是改變了別名,如果它是另一個。您還需要指定兩個表之間的連接條件。 (也注意到我在asc
之前添加了一個空格來停止將它連接到順序字符串中)。
這個編譯沒有錯誤;當運行時我得到ORA-00942:表或視圖不存在這是合理的。如果我創建虛擬數據:
create table tablea (some_col number, city varchar2(30));
create table tableb (some_col number);
insert into tablea values (1, 'London');
insert into tablea values (2, 'Londonderry');
insert into tablea values (3, 'East London');
insert into tablea values (4, 'New York');
insert into tableb values (1);
insert into tableb values (2);
insert into tableb values (3);
insert into tableb values (4);
然後調用它得到:
select myfunc('lond', 'city') from dual;
SOME_COL CITY SOME_COL
---------- ------------------------------ ----------
3 East London 3
1 London 1
2 Londonderry 2
如果你真的想與CTE堅持出於某種原因,然後(如@boneist說),需要成爲其中的一部分動態聲明:
OPEN v_result FOR
'with all_prb as (
select * from tableA ta
inner join tableB tb on tb.some_col = ta.some_col
)
select * from all_prb ff
where :p_city is null or LOWER(ff.city) like ''%''||:p_city||''%''
order by ' || p_order || ' asc'
using p_city, p_city;
爲什麼你使用'with'子句,爲什麼沒有連接條件? (您發佈的代碼獲得ORA-00905,而不是ORA-00928,所以這似乎不是你實際上運行的...) –
我試過立即執行('select * from all_prb ff where(:p_city爲null或(LOWER(ff.city)like''%''||:p_city ||''%''))order by || || p_order ||'asc'using p_city,p_city;)too and did not word我是這樣寫第一次動態sql所以如果你知道你可以寫我的代碼解決方案我怎麼寫? –
您已將光標的一部分創建爲靜態,並將其一部分創建爲動態。它必須是全部靜態或全部動態sql - 即你需要在動態sql中包含with子句。 – Boneist