Generic Function for Padding a Character in SQL Server
Padding character to a string is something which we use quite often in our day to day development activities and is what i found as a very good generic way of doing this -
CREATE FUNCTION dbo.fn_PadValue
(
@InValue varchar(50),
@PadLimit int,
@PadChar char(1),
@PadSide char(1)
)
RETURNS varchar(50)
AS
BEGIN
Declare
@Result varchar(50)
Declare
@Padding int
--Determine the
amount of padding
Set @Padding = @PadLimit - Len(@InValue)
IF @Padding < 0
Set
@Padding = 0
IF @PadSide = 'L' -- Pad the left side
Set @Result
= Replicate(@PadChar, @Padding) + @InValue
IF @PadSide = 'R' -- Pad the right side
Set @Result
= @InValue + Replicate(@PadChar, @Padding)
RETURN (@Result)
END
The Above code can be used in both LEFT and RIGHT side padding just by passing appropriate parameter to the function.
Usage --
select dbo.fn_PadValue('171',6,'0','L') --For Left Side Padding
select dbo.fn_PadValue('171',6,'0','R') --For Right
Side Padding
References -
http://www.sqlservercentral.com/scripts/T-SQL/64358/
Comments
Post a Comment