1

我有一个程序可以从某些表中选择 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,对于select,我需要使用“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;

不能因为 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 
);

你能告诉我如何处理这个不存在的异常序列吗?没关系,异常在错误的块中:)

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;
4

2 回答 2

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;
于 2012-04-26T07:20:51.493 回答
0

您不能使用变量作为表名。

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

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

于 2012-04-26T07:21:14.813 回答