整理DB2左补零,右补零的方法
在项目中经常遇到需要左补零,右补零的情况,在DB2实验环境中展示
1、左补零
(1)数字左补零,数字长度不定
用right(digits(cast(expression as bigint)),NUM)能实现,
注意:
①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的长度,则右侧补空格
举例展示:
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的长度,防止截断
2、右补零
(1)数字右补零,数字长度不定
(2)字符左补零,字符长度不定
右补零用DB2中已有的函数不好实现,现编写一SQL函数,在项目中可拿来使用
--/ 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 /
欢迎用本博客中的方法,解决项目中的补零需要
https://www.cnblogs.com/handhead/
莫问收获,但问耕耘