Oracle使用遊標查詢指定資料表的所有欄位名稱組合而成的字串,oracle遊標

來源:互聯網
上載者:User

Oracle使用遊標查詢指定資料表的所有欄位名稱組合而成的字串,oracle遊標

應用場合:參考網上查詢資料表的所有欄位名代碼,使用遊標產生指定單個表的所有欄位名跟逗號組成的用於select  逗號隔開的欄位名列表 from字串等場合。

查詢結果輸出如下:

當前資料表TB_UD_USER的欄位列表字串為
AH,BIRTHPLACE,BM,CELLPHONE,CJGZRQ,DEPARTMENT2,DJJID,GZCX,GZKH,GZSFZH,HJDZ,HYZK,ID,JHRQ,JTZZ,LAFX_LD,LJDZ,LLY,LXDH,NAME,NXDH,POLICENUMBER,RESERVE1,RESERVE10,RESERVE9,SCCP,SEX,SFJH,SFQBY,SFZ,SPJB,YL_22,ZJ,ZW,ZZMM
當前資料表TB_UD_USER查詢所有記錄語句為
select AH,BIRTHPLACE,BM,CELLPHONE,CJGZRQ,DEPARTMENT2,DJJID,GZCX,GZKH,GZSFZH,HJDZ,HYZK,ID,JHRQ,JTZZ,LAFX_LD,LJDZ,LLY,LXDH,NAME,NXDH,POLICENUMBER,RESERVE1,RESERVE10,RESERVE9,SCCP,SEX,SFJH,SFQBY,SFZ,SPJB,YL_22,ZJ,ZW,ZZMM from TB_UD_USER

詳細指令碼代碼如下:


--Oracle使用遊標查詢指定資料表的所有欄位名稱組合而成的字串

declare
mytablename NVARCHAR2(200):='TB_UD_USER'; --定義要查詢的資料表名稱變數
mystring NVARCHAR2(1000):=' '; --定義要輸出的欄位名稱列表字串變數  
selstring VARCHAR2(2000):=' '; --定義要輸出的查詢語句字串變數  

cursor mycursor is --定義遊標  

select distinct TABLE_COLUMN.*,TABLE_NALLABLE.DATA_TYPE,TABLE_NALLABLE.NULLABLE  from (select distinct utc.table_name  table_name, utc.comments    table_comments, ucc.column_name column_name, ucc.comments    column_comments from user_tab_comments utc, user_col_comments ucc  where utc.table_name = ucc.table_name  and utc.table_name not like '%_B'  and utc.table_name not like '%_Z'   and utc.table_name not like '%1%') TABLE_COLUMN,       (select distinct table_name, column_name, nullable, DATA_TYPE from user_tab_cols  where table_name not like '%_B'  and table_name not like '%_Z'  and table_name not like '%1%') TABLE_NALLABLE  where TABLE_COLUMN.column_name = TABLE_NALLABLE.column_name   and TABLE_COLUMN.TABLE_NAME = TABLE_NALLABLE.table_name  and TABLE_COLUMN.TABLE_NAME=mytablename  order by TABLE_COLUMN.TABLE_NAME,TABLE_COLUMN.column_name;

     
myrecord mycursor%rowtype;  --定義遊標記錄類型  
Counter int :=0;  
begin  
open mycursor;  --開啟遊標  
if mycursor%isopen  then  --判斷開啟成功  
loop --迴圈擷取記錄集    
fetch mycursor into myrecord; --擷取遊標中的記錄        

if mycursor%found then  --遊標的found屬性判斷是否有記錄 
begin
  --如果是第一個欄位
  if(mystring=' ') then
  mystring:=myrecord.column_name;
  else
  mystring:=mystring||','||myrecord.column_name;
  end if;

end;

else 

begin
 
dbms_output.put_line('當前資料表'||mytablename||'的欄位列表字串為');
dbms_output.put_line(mystring);

selstring:='select '||mystring||' from '||mytablename;

dbms_output.put_line('當前資料表'||mytablename||'查詢所有記錄語句為');
dbms_output.put_line(selstring);

exit;

end;

end if;
  
end loop;  
else    
dbms_output.put_line('遊標沒有開啟');  
end if; 

close mycursor;

end;

 

 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.