2013-12-09 110 views
1

我有創建函數的問題。我會盡量解釋一下是什麼問題:pl/sql:在oracle中選擇作爲函數的參數/參數

的任務是創造一種基於select first_name from employees where dept_id=10;功能。新功能必須有v_select_statement(這是我寫的)作爲參數(某事像這樣:v_select_statement := select first_name from employees where dept_id=10; Selet就像你可以看到生成的名稱列表,這些名稱應該是它在該函數創建過新表新表應具有名稱,如。 。NEW_TABLE 問題是,我不知道如何做到這一點我想是這樣的:。

create or replace 

FUNCTION create_new_tab (v_select_statement VARCHAR2) RETURN NUMBER 
is 
b first_name.employees%TYPE; 

begin 

--here i don`t know how to assign select statement to cursor or execute immediate. Any ideas? i tried create sth like: 
-- execute immediate 'v_select_statement into b '; 


execute immediate 'CREATE TABLE new_tab (i VARCHAR2(50))'; 
execute immediate 'insert into new_tab values (statement_result)'; 
--don`t know how and what to put as statement_result. I know that i could use cursor, but ---how in this case? 
return 1; 

exception 
when others then 
dbms_output.put_line(SQLERRM); 
return 0; 

END create_new_tab 
; 

你能幫助我,因爲我放棄了我不知道如何解決這個問題 如果你能幫幫我。

回答

0

這是您的referenec創建的函數。 我建議你什麼事先,然後創建一個表嘗試向其中插入數據。請嘗試此代碼,並讓我知道它是否適用於您。謝謝

Create or replace function test_func return number 
as 
cursor cr is select name from avrajit 
where department='.NET'; 
name_av avrajit.name%type; 
begin 
for rec in cr 
loop 
insert into av_test(dpt) values(rec.name); 
return 1; 
end loop; 
exception 
when others then 
return 0; 
end test_func; 
0

我不知道你的函數的目的是什麼。但是,如果你仍然想嘗試做這

create or replace 

FUNCTION create_new_tab (v_select_statement VARCHAR2) RETURN NUMBER 
is 
b first_name.employees%TYPE; 

begin 

--here i don`t know how to assign select statement to cursor or execute immediate. Any ideas? i tried create sth like: 
-- execute immediate 'v_select_statement into b '; 


execute immediate 'CREATE TABLE new_tab (i VARCHAR2(50))'; 
execute immediate 'insert into new_tab values (' || v_select_statement || ')'; --don`t know how and what to put as statement_result. I know that i could use cursor, but ---how in this case? 
return 1; 

exception 
when others then 
dbms_output.put_line(SQLERRM); 
return 0; 

END create_new_tab 
;` 
1

你可以做的是:

create or replace FUNCTION create_new_tab (v_select_statement VARCHAR2) RETURN NUMBER 
is 
b employees.first_name%TYPE; 
cur SYS_REFCURSOR; 

begin 
OPEN cur for v_select_statement; 

execute immediate 'CREATE TABLE new_tab (i VARCHAR2(50))'; 

LOOP 
    FETCH cur into b; 
    EXIT WHEN cur%NOTFOUND; 
    execute immediate 'insert into new_tab values (:statement_result)' USING b; 
END LOOP; 
CLOSE cur; 
return 1; 

exception 
when others then 
dbms_output.put_line(SQLERRM); 
return 0; 

END create_new_tab 
; 

沒有表無法測試它,但它可以爲你指明正確的方向。
但正如Avrajit已經說了,我會建議創建new_tab事前,然後插入無動態SQL該表normalle。
你還必須記住,這個功能只能運行一次,因爲這將導致一個錯誤,如果你嘗試創建表時它已經存在。