首页 > 代码库 > PadLeft 和 PadRight

PadLeft 和 PadRight

1 PadLeft

   即:向已知字符串左边补充字符,使整个字符串到达指定长度

 1 CREATE FUNCTION PadLeft 2 ( 3     @VarOrgan varchar(10),/*原始字符*/ 4     @TotalLength int,/*总长度*/ 5     @Placeholder varchar(1)/*占位符*/ 6 ) 7 RETURNS varchar(100) 8 AS 9 BEGIN10     declare @VarNew varchar(100),11             @PadLen int12     SET @VarNew=@VarOrgan13     SET @PadLen=@TotalLength-LEN(@VarOrgan)14     while(@PadLen>0)15         begin16             select @VarNew=@Placeholder+@VarNew17             set @PadLen=@PadLen-118         end19     return @VarNew20 END

 

2 PadRight

   即:向已知字符串右边补充字符,使整个字符串到达指定长度

 1 CREATE FUNCTION PadRight 2 ( 3     @VarOrgan varchar(10),/*原始字符*/ 4     @TotalLength int,/*总长度*/ 5     @Placeholder varchar(1)/*占位符*/ 6 ) 7 RETURNS varchar(100) 8 AS 9 BEGIN10     declare @VarNew varchar(100),11             @PadLen int12     SET @VarNew=@VarOrgan13     SET @PadLen=@TotalLength-LEN(@VarOrgan)14     while(@PadLen>0)15         begin16             select @VarNew=@VarNew+@Placeholder17             set @PadLen=@PadLen-118         end19     return @VarNew20 END

 

3 测试结果

SELECT dbo.PadLeft(7,6,0) PadLeft,        dbo.PadRight(6,4,0) PadRight

 

PadLeft 和 PadRight