Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

后端 未结 17 867
清歌不尽
清歌不尽 2020-11-22 08:13

I have a string that is up to 3 characters long when it\'s first created in SQL Server 2008 R2.

I would like to pad it with leading zeros, so if its original value w

17条回答
  •  伪装坚强ぢ
    2020-11-22 08:34

    Use this function which suits every situation.

    CREATE FUNCTION dbo.fnNumPadLeft (@input INT, @pad tinyint)
    RETURNS VARCHAR(250)
    AS BEGIN
        DECLARE @NumStr VARCHAR(250)
    
        SET @NumStr = LTRIM(@input)
    
        IF(@pad > LEN(@NumStr))
            SET @NumStr = REPLICATE('0', @Pad - LEN(@NumStr)) + @NumStr;
    
        RETURN @NumStr;
    END
    

    Sample output

    SELECT [dbo].[fnNumPadLeft] (2016,10) -- returns 0000002016
    SELECT [dbo].[fnNumPadLeft] (2016,5) -- returns 02016
    SELECT [dbo].[fnNumPadLeft] (2016,2) -- returns 2016
    SELECT [dbo].[fnNumPadLeft] (2016,0) -- returns 2016 
    

提交回复
热议问题