PadLeft number in SQL

/, SQL Server/PadLeft number in SQL

PadLeft accepts 3 parameters and returns a string that right aligns the characters.

  • Value: an integer number
  • PadChar: the character that will be used for the padding
  • Length: the length of the output
ALTER FUNCTION [dbo].[udf_PadLeftInt]
    (
     @Value INT
    ,@PadChar CHAR(1)
    ,@Length INT
    )
RETURNS VARCHAR(MAX)
AS 
    BEGIN
        DECLARE @ReturnValue AS VARCHAR(MAX);
        SET @ReturnValue = RIGHT(REPLICATE(@PadChar,@Length)
                                 + CAST(@Value AS VARCHAR(MAX)),@Length)
    
        RETURN @ReturnValue;
    END 
SELECT udf_PadLeftInt(10, '0', 5);

--output is 00010
2017-03-05T13:52:24+00:00 January 10th, 2017|SQL, SQL Server|0 Comments

Leave A Comment