2016-01-06 81 views
0

以下函數有什麼問題?動態使用select into語句

create or replace function getNameById(myId in number) return number 
is 
    query varchar2(500); 
    myName varchar2(20); 
begin 


    query :='SELECT users_name INTO :myname FROM USERS_TABLE WHERE USERS_ID = :myid'; 

    execute 
    immediate query 
    USING out myName, myId; 

    dbms_output.put_line(myName); 
    return(myName); 
end getNameById; 

如果不是查詢我使用:

SELECT users_name INTO myName FROM USERS_TABLE WHERE USERS_ID = 81; 

執行然而成功

問題是,當我添加 「INTO:MYNAME」 我在執行得到一個錯誤..

在動態sql中使用INTO是不可能的?

編輯:解決了!

create or replace function getNameById(myId in number) return varchar2 
is 
    query varchar2(500); 
    myName users_table.users_name%type; 

begin 

    query :='SELECT users_name FROM USERS_TABLE WHERE USERS_ID = :myid'; 
    execute immediate query INTO myName USING myId; 

    dbms_output.put_line(myName); 
    return(myName); 

end getNameById; 

回答

0

您不能在Oracle動態SQL中綁定表名。您需要將表名直接放入動態SQL中。嘗試使用以下存儲過程,而不是:

CREATE OR REPLACE PROCEDURE getNameById (
    myName IN VARCHAR2, 
    myId IN NUMBER) AS 
    where_clause VARCHAR2(100) := ' WHERE USERS_ID = ' || myId; 
BEGIN 
    EXECUTE IMMEDIATE 'SELECT users_name INTO ' || myname || ' FROM USERS_TABLE' || where_clause; 
END; 

閱讀herehere以獲取更多信息。

2

你並不需要使用到你的SELECT語句

create or replace function getNameById(myId in number) return number 
is 
    query varchar2(500); 
    myName varchar2(20); 
    rezult varchar(100); 
begin 

    query :='SELECT users_name FROM USERS_TABLE WHERE USERS_ID = '||myid; 

     execute 
     immediate query 
     into rezult; 

    dbms_output.put_line(rezult); 
    return(rezult); 
end getNameById;