Technical Article

User Defined Function for Padding Numbers

,

This scalar udf takes three parameters @Number INT, @Length INT, @Position CHAR(1) and returns a VARCHAR(50) string which pads @Number with zeros to the specified @Length either to the right or to the left, according to @Position ('L' or 'R').
E.g. SELECT dbo.udf_PadNumber(5, 6, 'L') returns '000005' whereas SELECT dbo.udf_PadNumber(5, 6, 'R') returns '500000'. The function is thus equivalent to the PadToLeft() or PadToRight() string functions familiar in C Sharp.
The function as it appears here has minimal error handling. It would be trivial to extend the function to include a parameter for the character (e.g. 'X' instead of zero) to be used for padding the string.

The function can be used in SELECT statements where an ID column value could be returned in a more user-friendly format.

CREATE FUNCTION [dbo].[udf_PadNumber]
 (
@Number INT,
@Length INT,
@Position CHAR(1)
)  
RETURNS VARCHAR(50) AS

BEGIN 
IF@Length >= @Number
DECLARE@PaddedNr VARCHAR(50)

SELECT@PaddedNr =
CASE UPPER(@Position)
WHEN 'L' 
THEN
 REPLACE(SPACE((@Length-LEN(@Number))), ' ', '0') + CAST(@Number AS VARCHAR(6))
WHEN 'R'
THEN
 CAST(@Number AS VARCHAR(6)) + REPLACE(SPACE((@Length-LEN(@Number))), ' ', '0')
ELSE
'N/A'
END
RETURN@PaddedNr
END

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating