整理DB2左補零,右補零的方法

在項目中常常遇到須要左補零,右補零的狀況,在DB2實驗環境中展現git

一、左補零
(1)數字左補零,數字長度不定
用right(digits(cast(expression as bigint)),NUM)能實現,express


注意:
①right(expression,NUM):表示從"expression"的右側第一個字符取,取滿NUM位,若不足NUM位左側補零
②digits():返回SMALLINT、INTEGER、BIGINT或者DECIMAL的字符串值
其中smallint:返回5位字符串,INTEGER返回10位字符串,BIGINT返回19位字符串,DECIMAL返回31位字符串
③cast(expression as bigint):強制類型轉換
④若NUM>bigint的長度,則右側補空格函數


舉例展現:fetch

select
right(digits(cast(12345 as smallint)),20) SMALL_Value,Length(right(digits(cast(12345 as smallint)),20)) Length_Value,/*smallint佔5位,Length_Value=20, digits(cast(12345 as smallint))不足20位的部分右側用空格補齊*/
right(digits(cast(12345 as integer)),20) integer_Value,Length(right(digits(cast(12345 as integer)),20))integer_Length,/*INTEGER佔10位,integer_Length=20,
digits(cast(12345 as integer))不足20位的部分右側用空格補齊
*/ right(digits(cast(12345 as bigint)),20) bigint_Value,Length(right(digits(cast(12345 as bigint)),20))bigint_Length,/*BIGINT佔10位,bigint_Length=20,
digits(cast(12345 as bigint))不足20位的部分右側用空格補齊
*/ from syscat.tables fetch first 1 rows only;

 

(2)字符左補零,字符長度不定
用right(digits(cast(expression as varchar(NUM_IN))),NUM)能實現,
注意:
①NUM_IN>expression的長度,防止截斷
②NUM>NUM_IN的長度,防止截斷spa

二、右補零
(1)數字右補零,數字長度不定
(2)字符左補零,字符長度不定code

右補零用DB2中已有的函數很差實現,現編寫一SQL函數,在項目中可拿來使用blog

--/
CREATE function RightComZero(In_Varchar(1800),Num_Len integer) RETURNS VARCHAR(1800) LANGUAGE SQL BEGIN ATOMIC DECLARE Varchar_Length Bigint; DECLARE MID_Varchar Varchar(1800); DECLARE FIN_Varchar Varchar(1800); DECLARE DIFF_Length Bigint; SET Varchar_Length =0; SET DIFF_Length =0; SET MID_Varchar =Rtrim(Ltrim(In_Varchar)); SET Varchar_Length =Length(MID_Varchar ); IF(Varchar_Length =0 or Varchar_Length >Num_Len) THEN
    SET FIN_Varchar ='!'; return FIN_Varchar ; ELSE
    SET DIFF_Length =Num_Len-Varchar_Length ; SET FIN_Varchar =MID_Varchar ; END IF; WHILE  DIFF_Length >0 DO SET FIN_Varchar =FIN_Varchar ||'0'; SET DIFF_Length =DIFF_Length -1; END WHILE; RETURN FIN_Varchar ; END
/

歡迎用本博客中的方法,解決項目中的補零須要字符串

相關文章
相關標籤/搜索