1. PadLeft function
Adds a character to the left of a known string to make the entire string reach the specified length
CREATE FUNCTIONPadLeft (@VarOrgan varchar(Ten),/*Original Character*/ @TotalLength int,/*Total length*/ @Placeholder varchar(1)/*placeholder*/)RETURNS varchar( -) asBEGIN Declare @VarNew varchar( -), @PadLen int SET @VarNew=@VarOrgan SET @PadLen=@TotalLength-LEN(@VarOrgan) while(@PadLen>0) begin Select @VarNew=@Placeholder+@VarNew Set @PadLen=@PadLen-1 End return @VarNewEND
2, PadRight
Complements the character to the right of the known string, making the entire string reach the specified length
CREATE FUNCTIONPadRight (@VarOrgan varchar(Ten),/*Original Character*/ @TotalLength int,/*Total length*/ @Placeholder varchar(1)/*placeholder*/)RETURNS varchar( -) asBEGIN Declare @VarNew varchar( -), @PadLen int SET @VarNew=@VarOrgan SET @PadLen=@TotalLength-LEN(@VarOrgan) while(@PadLen>0) begin Select @VarNew=@VarNew+@Placeholder Set @PadLen=@PadLen-1 End return @VarNewEND
SELECT dbo. PadLeft (' 7 ', 6, ' 0 ') PadLeft,
Dbo. PadRight (' 6 ', 4, ' 0 ') padright
SQL functions PadLeft and PadRight code instances