无法找到光标和表格

时间:2012-04-26 07:11:08

标签: sql oracle plsql cursor

我有一个从某些表中选择MAX的过程,但由于某种原因它无法找到这些表。有人能帮助我吗?

declare
varible1 varchar2 (255);
temp varchar2 (255);
last_val number(9,0);
 cursor c1 is Select distinct table_name from user_tab_cols order by table_name;
begin
FOR asd in c1
LOOP
temp := asd.table_name;
varible1  := '"'||temp||'"';
select max("id") into last_val from varible1 ;
END LOOP;
end;

例如,第一个表名是acceptance_form,而选择我需要使用“acceptance_form”。

编辑后的代码:

declare
varible1 varchar2 (255);
temp varchar2 (255);
last_val number(9,0);
 cursor c1 is Select distinct table_name from user_tab_cols where column_name = 'id';
begin
FOR asd in c1
LOOP
temp := asd.table_name;
execute immediate 'select NVL(max('||'id'||'),0) from "'||varible1||'"' into last_val;
END LOOP;
end;

不能cuz db是区分大小写的Oracle Express 10g表和行就是这样创建的

CREATE TABLE "ADMINMME"."acceptance_form"
(
    "group_id" NUMBER(9, 0), 
    "id" NUMBER(4, 0) DEFAULT '0' NOT NULL , 
    "is_deleted" NUMBER(4, 0), 
    "name" NVARCHAR2(30) NOT NULL 
);

你能告诉我如何处理异常序列吗? Nevermind异常是在错误的块中:)

declare
temp varchar2 (255);
last_val number(9,0);
 cursor c1 is Select distinct table_name from user_tab_cols where column_name = 'id';
begin
FOR asd in c1
LOOP
temp := asd.table_name;
execute immediate 'select NVL(max("id"),0)+1 from "'||temp||'"' into last_val;
begin
EXECUTE IMMEDIATE 'drop sequence "seq_'|| temp||'"';
EXECUTE IMMEDIATE 'create SEQUENCE "seq_'|| temp ||'" MINVALUE '||last_val||'MAXVALUE                 999999999999999999999999999 INCREMENT BY 1 NOCACHE';
EXECUTE IMMEDIATE 'select '||temp||'.nextval from dual';
EXECUTE IMMEDIATE 'ALTER SEQUENCE "seq_'||temp||'" INCREMENT BY 1';
exception when others then
null;
end;
END LOOP;
end;

2 个答案:

答案 0 :(得分:3)

动态sql不能以这种方式工作。

declare
varible1 varchar2 (255);
temp varchar2 (255);
last_val number(9,0);
 cursor c1 is Select distinct table_name from user_tab_cols order by table_name;
begin
  FOR asd in c1
  LOOP
  temp := asd.table_name;
  begin
    execute immediate 'select max(id) from '||temp into last_val;
    dbms_output.put_line('max(id) for table: ' ||temp||' = '||last_val);
  exception when others then
     dbms_output.put_line('Failed to get max(id) for table: ' ||temp);
  end;
  END LOOP;
end;

答案 1 :(得分:0)

您不能将变量用于表名。

您可以做的是将完整的sql语句创建为字符串并使用execute immediate

以下是一些示例:http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/dynamic.htm#CHDGJEGD