我想写个存储过程,从表里查询很多条数据,表名是随时间变化的!
表结构如下,表名为‘计量点表码表200701’,每个月都有一个表,如‘计量点表码表200702’ 等等。
create table 计量点表码表200701 (
     计量点编码                NUMBER(6)                     not null,
     费率类型                 NUMBER(2)                     not null,
     时间                   DATE                  not null,
     正向有功                 NUMBER(10)                    null,
         primary key (计量点编码, 费率类型, 时间))我就想取所有字段的数据,是肯定得用游标取了!
各位多帮忙,谢谢了!对于ORACLE数据库还是第一次接触,真的是不会写啊!

解决方案 »

  1.   

    和普通的过程一样,不过查询用动态语句执行即可\
    execute immediate 'SQL'
      

  2.   

    给你个例子 ...create or replace procedure sp_test(p_date in varchar2) is
    type t_cursor is ref cursor;
    v_str varchar(1000);
    v_cur t_cursor;
    r_cur 计量点表码表200701%rowtype;
    begin
     v_str := 'select * from 计量点表码表'||p_date||' ';
     open v_cur for v_str;
     loop
     Fetch v_cur into r_cur;
     exit when v_cur%notfound;
     dbms_output.put_line('the result is: '||r_cur.计量点编码||' '||r_cur.费率类型);
     end loop;
     close v_cur;
    end sp_test;
      

  3.   

    我来补充具体点,在存储过程中,将表名作为字符串类型参数,再声明一个用来存储sql语句的字符串,在用到表名的地方用字符串连接符:||表名||,最后执行execute immediate  存储sql的字符串,执行前最好用dbms_output出你的sql语句查看一下是否正确.
      

  4.   

    用execute immediate执行动态的sql
      

  5.   

    declare   @name   varchar(20) declare   t_cursor   cursor   for   
    select   name   from   syscolumns   
    where   id=object_id( 'test1 ')   and   colid> 1   order   by   colid open   t_cursor fetch   next   from   t_cursor   into   @name while   @@fetch_status=0 
    begin 
            exec( 'select   '+@name+ '   as   t   into   test3   from   test1 ') 
            set   @s= 'insert   into   test2   select   ' ' '+@name+ ' ' ' ' 
            select   @s=@s+ ', ' ' '+rtrim(t)+ ' ' ' '   from   test3 
            exec(@s) 
            exec( 'drop   table   test3 ') 
            fetch   next   from   t_cursor   into   @name 
    end 
    close   t_cursor 
    deallocate   t_cursor