ORA-01007:变量不在选择列表-1007中

时间:2016-09-27 08:09:54

标签: oracle plsql dynamic-sql

我有下表:

CREATE TABLE req1_tb(TableName  VARCHAR2(43),
                    ColumnName  VARCHAR2(98),
                    Edit_ind    CHAR)

这是此表的dml:

insert into req1_tb VALUES('Employees','employee_id','Y');
insert into req1_tb VALUES('Employees','first_name','Y');
insert into req1_tb VALUES('Employees','last_name','N');
insert into req1_tb VALUES('Employees','email','N');
insert into req1_tb VALUES('Employees','job_id','N');
insert into req1_tb VALUES('Employees','salary','Y');
insert into req1_tb VALUES('Employees','commission_pct','Y');
insert into req1_tb VALUES('Employees','hire_date','N');
insert into req1_tb VALUES('Employees','department_id','Y');

我认为表格enter code here中的edit_ind列会动态更改

SQL> SELECT * FROM REQ1_TB;

TABLENAME                                   COLUMNNAME      EDIT_IND
------------------------------------------- --------------- ----------
Employees                                   employee_id     Y
Employees                                   first_name      Y
Employees                                   last_name       N
Employees                                   email           N
Employees                                   job_id          N
Employees                                   salary          Y
Employees                                   commission_pct  Y
Employees                                   hire_date       N
Employees                                   department_id   Y

我创建的程序将动态打印仅标记为“Y”的列:

CREATE OR REPLACE PROCEDURE dyn_sql_sp
 AS
  cols     VARCHAR2(2000);
  v_cols   VARCHAR2(2000);
  cls      VARCHAR2(2000);
  v_employee_id number;
  emp       employees%rowtype;
  cnt       number;
 cursor tab_c
 is
  select columnname from req1_tb
  where EDIT_IND='Y';
 cursor col_c
 is
  select employee_id from employees;
 BEGIN
 for i in tab_C
 loop
 cols:=cols||'emp.'||i.columnname||',';
 end loop;
 cols:=rtrim(cols,',');
for i in col_c
 loop
EXECUTE IMMEDIATE 'SELECT ' || cols || ' FROM employees WHERE employee_id = :1'
INTO emp
USING i.employee_id;
 end loop;
 dbms_output.put_line(cols);
  Exception
  When Others Then
  dbms_output.put_line(sqlerrm||sqlcode);
  end;
/

执行时我收到以下错误:

SQL> exec dyn_sql_sp;
ORA-01007: variable not in select list-1007

1 个答案:

答案 0 :(得分:1)

在您的程序中,以下代码将产生问题。据我所知,您正在尝试根据表columns中的employee标记选择表'Y'的{​​{1}}。

有问题的部分:

req1_tb

现在,在声明一个变量来保存从for i in col_c loop EXECUTE IMMEDIATE 'SELECT ' || cols || ' FROM employees WHERE employee_id = :1' --***The INTO clause is problematic here. Since the you select list is not*** having all the columns same as your cursor variable. INTO emp USING i.employee_id; end loop; 语句中的那些选定列返回的数据时,您没有尝试相同的逻辑。

为此,变量声明也应该是动态的。所以你声明

  

emp employees%rowtype;

应该使得所有选定的列都满足条件标志Execute Immediate。您不能将从select语句中选择的几列插入到具有所有列的游标变量中。