如何使用DBMS_SQL从表中进行选择

时间:2016-01-05 12:57:52

标签: plsql

我正在尝试使用dbms_sql包从表中进行选择,但我不能这样做..有谁能告诉我我做错了什么?

create or replace function dbsm_sql_SELECT(age IN NUMBER) return VARCHAR2 is



 q VARCHAR2(500);
  ret NUMBER;
  c1 number;

begin
  q := 'SELECT users_name FROM USERS_TABLE WHERE USERS_AGE = :1';

  c1 := dbms_sql.open_cursor;

  dbms_sql.parse(c1,q,dbms_sql.native);
  dbms_sql.bind_variable(c => c1, name => ':1' , value => age );

  ret := dbms_sql.execute(c1);
  dbms_sql.close_cursor(c1);

  dbms_output.put_line(ret);
  return('a');
end dbsm_sql_SELECT;

1 个答案:

答案 0 :(得分:0)

这里..尝试这个..我已经切换到查询公共表

clear screen
SET serveroutput ON size 1000000

declare
function dbsm_sql_SELECT(age IN NUMBER) return VARCHAR2 is



 q VARCHAR2(500);
  ret NUMBER;
  c1 number;

  l_username VARCHAR2(40);

begin
  q := 'SELECT username FROM user_USERS WHERE user_id < :1';

  c1 := dbms_sql.open_cursor;

  dbms_sql.parse(c1,q,dbms_sql.native);

  DBMS_SQL.DEFINE_COLUMN(c1, 1, l_username,40); 
  --define any other columns you want

  dbms_sql.bind_variable(c => c1, name => ':1' , value => age );


  ret := dbms_sql.execute(c1);

  LOOP 
       IF DBMS_SQL.FETCH_ROWS(c1)>0 THEN 
        DBMS_SQL.COLUMN_VALUE(c1, 1, l_username); 
        --get values of any columns you previously defined

      ELSE 

  -- No more rows to copy: 
        EXIT; 
      END IF; 
  end loop;

  dbms_sql.close_cursor(c1);

  dbms_output.put_line(ret);
  --return teh correct value
  return(l_username);
end ;

begin

dbms_output.put_line(dbsm_sql_SELECT(1000));
end;
/