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

后端 未结 17 905
清歌不尽
清歌不尽 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:22

    I created this function which caters for bigint and one leading zero or other single character (max 20 chars returned) and allows for length of results less than length of input number:

    create FUNCTION fnPadNum (
      @Num BIGINT --Number to be padded, @sLen BIGINT --Total length of results , @PadChar varchar(1))
      RETURNS VARCHAR(20)
      AS
      --Pads bigint with leading 0's
                --Sample:  "select dbo.fnPadNum(201,5,'0')" returns "00201"
                --Sample:  "select dbo.fnPadNum(201,5,'*')" returns "**201"
                --Sample:  "select dbo.fnPadNum(201,5,' ')" returns "  201"
       BEGIN
         DECLARE @Results VARCHAR(20)
         SELECT @Results = CASE 
         WHEN @sLen >= len(ISNULL(@Num, 0))
         THEN replicate(@PadChar, @sLen - len(@Num)) + CAST(ISNULL(@Num, 0) AS VARCHAR)
         ELSE CAST(ISNULL(@Num, 0) AS VARCHAR)
         END
    
         RETURN @Results
         END
         GO
    
         --Usage:
          SELECT dbo.fnPadNum(201, 5,'0')
          SELECT dbo.fnPadNum(201, 5,'*')
          SELECT dbo.fnPadNum(201, 5,' ')
    

提交回复
热议问题