2

在种子数据填充我们的表后,我们有一个 sql 脚本来更新一组序列。下面的代码不起作用:

declare
cursor c1 is 
    select
      'select nvl(max(id),0) from '||uc.table_name sql_text,
      uc.table_name||'_SEQ' sequence_name 
    from
      user_constraints uc,
      user_cons_columns ucc
    where uc.constraint_type='P'
      and ucc.constraint_name = uc.constraint_name
      and ucc.column_name='ID'
      and uc.owner='ME';

alter_sequence_text varchar2(1024);
TYPE generic_cursor_type IS REF CURSOR;
max_id number;
c2 generic_cursor_type;
begin
for r1 in c1 loop
    open c2 for r1.sql_text;
    fetch c2 into max_id;
    close c2;

    if( max_id != 0 ) then
        dbms_output.put_line( 'seq name = '||r1.sequence_name );
        execute immediate 'alter sequence '||r1.sequence_name||' increment by '||to_char(max_id);
        dbms_output.put_line( 'max_id = '||to_char(max_id) );
        execute immediate 'select '||r1.sequence_name||'.nextval from dual';
        dbms_output.put_line( 'sequence value = '||to_char(next_id) );
        execute immediate 'alter sequence '||r1.sequence_name||' increment by 1';
        dbms_output.put_line( 'sequence: '||r1.sequence_name||' is at '||to_char(max_id+1) );
    end if;
end loop;
end;

搜索后,我找到了一个说明我需要更改行的参考:

execute immediate 'select '||r1.sequence_name||'.nextval from dual'

并添加'到 next_id;' (当然适当地声明 next_id )所以结果将是:

execute immediate 'select '||r1.sequence_name||'.nextval from dual into next_id;

我一般只简单地处理了 pl/sql 和 sql,并且很想知道为什么要使脚本正常工作需要进行此更改。

谢谢。

4

2 回答 2

2

当您使用select内部PL/SQL块时,您必须将该选择语句返回的数据放在某处。因此,您必须声明一个适当数据类型的变量并使用select into子句将数据选择返回到该变量中,即使select语句是按execute immediate语句执行的。

例子

declare
  x number;
begin
  select count(*)
    into x
    from all_objects;
end;


declare
  x number;
begin
  execute immediate 'select count(*)from all_objects' into x;
end;

所以你的execute immediate陈述是

execute immediate 'select '||sequence_name||'.nextval from dual' into newseqval;

如果您使用 Oracle 11g 以后的版本,您可以将序列的值直接分配给变量,不需要 usingselect into子句。

 declare
   x number;
 begin
   x := Sequence_Name.nextval;
 end;
于 2012-09-23T07:18:01.813 回答
0

select seq_name.nextval from dual 意味着隐式游标的创建,并且游标的结果应该在某处获取,因此您需要将其获取到任何外部声明的绑定变量中。

于 2012-09-23T06:42:47.573 回答