动态使用select into语句

时间:2016-01-06 09:31:09

标签: plsql

以下功能有什么问题?

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;

2 个答案:

答案 0 :(得分:2)

您无需在select语句中使用into

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;

答案 1 :(得分: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了解详情。