Oracle函式-->字元處理

derekzhan發表於2010-07-29

取得字串長度:

用lengthb()以位元組為單位
用length()以字元為單位

擷取字串:substr

oracle中,可以用substr函式擷取字串.

語法:
substr( string, start_position, [ length ] )
取子字串,從start_position開始,取length個,length為可選,如果length為空則返回start_position後的所有字元。

例項:

    substr('This is a test', 6, 2)          would return 'is'
    substr
('This is a test', 6)              would return 'is a test'
    substr
('TechOnTheNet', 1, 4)     would return 'Tech'
    substr
('TechOnTheNet', -3, 3)    would return 'Net'
    substr
('TechOnTheNet', -6, 3)    would return 'The'
    substr
('TechOnTheNet', -8, 2)    would return 'On'

select substr('TechOnTheNet', -3, 2) from dual
start
_position為負數時,表示從字串尾巴倒著數。

 

在oracle的資料庫裡有個函式 LPAD(String a,int length,String addString). 

  作用:把addString新增到a的左邊,length 是返回值的長度。 

例子 

   A : SQL> select lpad('test',8,0) from dual; 

         LPAD('TEST',8,0)
                    ----------------
                 0000test 

        B: select lpad('test',8) from dual;

              LPAD('TEST',8)
                         -------------- 
      【    test】 注:不寫最後一個引數,函式會預設在返回值左邊加一個空格。

               C: SQL> select lpad('test',2,0) from dual;

                LPAD('TEST',2,0)
                ----------------
              te

              D:SQL> select lpad('test',3) from dual;

                   LPAD('TEST',3)
                  --------------
                    tes

語法:LPAD(expr,n[,pad])

RPAD(expr,n[,pad])

e.g.

select lpad('hello',8,'xy') from dual ='xyxhello'

select lpad('我是一個兵',20,'xy') from dual  ='xyxyxyxyxy我是一個兵'

select lpad('hello',4,'xy') from dual ='hell'

即如果n小於字串的個數(一個漢字等於兩個普通字串),則會取自左到右n個字元。如果大於,則在字串左邊按順序迴圈從‘xy’取值,返回字串的個數是n。

select rpad('hello',8,'xy') from dual ='helloxyx'

select rpad('hello',4,'xy') from dual ='hell'

即如果n小於字串的值,則兩個函式返回值是一樣的。

相關文章