1. 程式人生 > >oracle 行轉列(用函式和遊標完成)

oracle 行轉列(用函式和遊標完成)

create table students
(student_id  varchar2(32),
student_name varchar2(180),
student_age number
)
insert into students values('1','金瑞','14');
insert into students values('2','中軍','15');
insert into students values('3','於瑞','14');
insert into students values('4','快樂','14');
insert into students values('5','劉強','14');
insert into students values('6','紅豆','14');
insert into students values('7','張明','14');
insert into students values('8','宿遷','14');
insert into students values('9','藍蝶','14');
insert into students values('0','奇美','14');
-- 行轉列 將多行資料轉換為一列。例如學生表中將學生姓名串起來
create or replace
function getStudentNameString
  return varchar2 as
  begin
    declare cursor cu_student is
    select student_name from students order by student_id;
    student_name varchar2(180);
    rowString varchar2(1000);
    
    begin
      open cu_student;
      fetch cu_student into student_name;
      while cu_student%found loop
        rowString :=rowString || student_name || ',';
        fetch cu_student into student_name;
       end loop;
       return substr(rowString,1,length(rowString)-1);
      end;
     end getStudentNameString;
-- 測試
select getStudentNameString() from dual;
-- 程式碼說明
 declare cursor cu_student is select student_name from students order by student_id;
用於宣告一個遊標,該遊標可用於迴圈獲得資料表中所有學生姓名記錄;

 fetch cu_student into student_name;
 用於將遊標所指向的當前記錄的資料賦值給student_name;
 
 while cu_student%found loop
   用於迴圈處理遊標所指向的記錄;
  
 rowString :=rowString || student_name || ',';
 用於將變數student_name的值新增到rowString的末尾。