DB2中REVERSE函數的實現

來源:互聯網
上載者:User

DB2中REVERSE函數的實現

有哥們在群裡問DB2有沒有內建的reverse函數,我測試一下,DB2確實內建該函數,但是Oracle,sql server都內建了該函數,來看一下

ORACLE:

SQL> select reverse('1234') from dual;

REVERSE(
--------
4321

SQL> select reverse(12121) from dual;
select reverse(12121) from dual
              *
第 1 行出現錯誤:
ORA-00932: 資料類型不一致: 應為 CHAR, 但卻獲得 NUMBER

說明oracle中reverse的參數是char類型,傳回值也是char,到底是不是這樣,我們來驗證一下

SQL> select length(reverse('1234    ')) from dual;

LENGTH(REVERSE('1234'))
-----------------------
                      8

SQL> select reverse('1234    ') from dual;

REVERSE('1234')
----------------
    4321

如果傳回型別是varchar,長度應該是4,所以傳回值是char。參數類型也應該是是char。

sql server:

DB2中REVERSE函數的實現

reverse函數的參數類型varchar或nvarchar,傳回型別也是varchar或nvarchar

C:\>sqlcmd -S kermart -U sa -P sa -d master
1> select reverse('1234');
2> go

----
4321

(1 行受影響)
1> select reverse(1234);  --發生類型轉換,應該可以從執行計畫中看出來
2> go

------------
4321

(1 行受影響)

 

基於oracle,sql server都內建了reverse函數,DB2也應該有它的reverse函數,因為有一定的應用情境。

CREATE OR REPLACE  FUNCTION REVERSE
(
  p1 varchar(200)
)
  RETURNS VARCHAR(200)
  SPECIFIC "REVERSE"
  LANGUAGE SQL
  DETERMINISTIC
  NO EXTERNAL ACTION
  READS SQL DATA
BEGIN

  declare v_str varchar(100) default '';
  DECLARE v_index INTEGER;      --定義下標
  SET v_index = length(p1);
  WHILE(v_index >= 1)  DO
      SET v_str = v_str||substr(p1,v_index,1);
      SET v_index = v_index - 1;
  END WHILE;
  return v_str;
END@

測試一下

select reverse('123456') from dual;

654321

select reverse(1234) from dual;  --看執行計畫,應該可以看到類型轉換

4321

本文永久更新連結地址:

相關文章

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.