如何为表的所有列创建循环?

时间:2012-11-23 06:59:33

标签: oracle loops select plsql

我有一个表EMPLOYEES,我需要循环,在循环的每一步我使用dbms_output.put_line(column_name)

我该怎么做?

3 个答案:

答案 0 :(得分:2)

刚刚找到这个解决方案

begin
   for rec in (SELECT column_name 
               FROM all_tab_columns 
               WHERE owner = 'HR'
               AND table_name = 'EMPLOYEES')
   loop
       dbms_output.put_line(rec.column_name);
   end loop;
end;

答案 1 :(得分:0)

尝试使用光标如下:

set serveroutput on;
declare
 var_col1 varchar2(30) ;
 num_col2 number ;  

 CURSOR cur
 is       
  select var_col ,num_col
  from table
  where <conditions>;

begin
   open cur;
   fetch cur into var_col1,num_col2;

   LOOP
    fetch cur into var_col1,num_col2;
       EXIT WHEN cur%NOTFOUND;
       dbms_output.put_line( var_col1||'         '||num_col2);
   END LOOP;

   close cur;  
end;

这是另一种解决方案:

set serveroutput on;
begin
  FOR  cur in ( select var_col ,num_col from table where <conditions>)
  LOOP
    dbms_output.put_line(cur.var_col||' = '||cur.num_col);
  END LOOP;
end;

答案 2 :(得分:0)

当然,您可以在table_name之后使用WHERE重写此SELECT示例。我没有编译这个代码,但我认为它没关系。更改属性的ID_Employee和Name

CREATE OR REPLACE PROCEDURE AAA_TEST
    IS
    BEGIN
      DECLARE 
            v_id NUMBER :=0;
            v_name VARCHAR2(25);

            CURSOR cursorMails IS
                 SELECT Id_Employee,Name FROM EMPLOYEES;  

            BEGIN
                           OPEN cursorMails;

                               LOOP

                                    FETCH cursorMails INTO v_id, v_name;
                                         DBMS_OUTPUT.PUT_LINE('Number of Employee: ' || v_id || ' Name Employee: ' || v_name);
                               EXIT WHEN cursorMails%NOTFOUND;
                               END LOOP;
                           CLOSE cursorMails;
            END;
    END;
    /