熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Oracle >> 正文

淺議Oracle中的進制轉換

2022-06-13   來源: Oracle 

  進制轉換是開發中經常需要用到的本文簡單介紹幾種常用的進制轉化方法
  
  進制轉換為進制
  
  可以通過to_number函數實現
  
  SQL> select to_number(fxxx) from dual;
  TO_NUMBER(FXXX)
  
  
  SQL> select to_number(fxx) from dual;
  TO_NUMBER(FXX)
  
  
  
  進制轉換為進制
  
  可以通過to_char函數轉換
  
  SQL> select to_char(xxx) from dual;
  TO_C
  
  b
  SQL> select to_char(xxxx) from dual;
  TO_CH
  
  d
  
  進制轉換為進制
  
  從Oraclei開始提供函數bin_to_num進行進制到進制的轉換
  
  SQL> select bin_to_num() abin_to_num() b from dual;
  A B
  
  
  SQL> select bin_to_num() from dual;
  BIN_TO_NUM()
  
  
  
  四 通過自定義函數實現進制轉換
  
  以下函數來自AskTom網站是Tom給出的例子供參考:
  
  create or replace function to_base( p_dec in number p_base in number )
  return varchar
  is
  l_str varchar() default NULL;
  l_num number default p_dec;
  l_hex varchar() default ABCDEF;
  begin
  if ( trunc(p_dec) <> p_dec OR p_dec < ) then
  raise PROGRAM_ERROR;
  end if;
  loop
  l_str := substr( l_hex mod(l_nump_base)+ ) || l_str;
  l_num := trunc( l_num/p_base );
  exit when ( l_num = );
  end loop;
  return l_str;
  end to_base;
  /
  create or replace function to_dec
  
  ( p_str in varchar
  p_from_base in number default ) return number
  is
  l_num number default ;
  l_hex varchar() default ABCDEF;
  begin
  for i in length(p_str) loop
  l_num := l_num * p_from_base + instr(l_hexupper(substr(p_stri)));
  end loop;
  return l_num;
  end to_dec;
  /
  show errors
  create or replace function to_hex( p_dec in number ) return varchar
  is
  begin
  return to_base( p_dec );
  end to_hex;
  /
  create or replace function to_bin( p_dec in number ) return varchar
  is
  begin
  return to_base( p_dec );
  end to_bin;
  /
  create or replace function to_oct( p_dec in number ) return varchar
  is
  begin
  return to_base( p_dec );
  end to_oct;
  /
From:http://tw.wingwit.com/Article/program/Oracle/201311/16962.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.