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

后端 未结 17 897
清歌不尽
清歌不尽 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,' ')
    
    0 讨论(0)
  • 2020-11-22 08:26

    I came here specifically to work out how I could convert my timezoneoffset to a timezone string for converting dates to DATETIMEOFFSET in SQL Server 2008. Gross, but necessary.

    So I need 1 method that will cope with negative and positive numbers, formatting them to two characters with a leading zero if needed. Anons answer got me close, but negative timezone values would come out as 0-5 rather than the required -05

    So with a bit of a tweak on his answer, this works for all timezone hour conversions

    DECLARE @n INT = 13 -- Works with -13, -5, 0, 5, etc
    SELECT CASE 
        WHEN @n < 0 THEN '-' + REPLACE(STR(@n * -1 ,2),' ','0') 
        ELSE '+' + REPLACE(STR(@n,2),' ','0') END + ':00'
    
    0 讨论(0)
  • 2020-11-22 08:28

    For a more dynamic approach try this.

    declare @val varchar(5)
    declare @maxSpaces int
    set @maxSpaces = 3
    set @val = '3'
    select concat(REPLICATE('0',@maxSpaces-len(@val)),@val)
    
    0 讨论(0)
  • 2020-11-22 08:30

    Simple is that

    Like:

    DECLARE @DUENO BIGINT
    SET @DUENO=5
    
    SELECT 'ND'+STUFF('000000',6-LEN(RTRIM(@DueNo))+1,LEN(RTRIM(@DueNo)),RTRIM(@DueNo)) DUENO
    
    0 讨论(0)
  • 2020-11-22 08:33

    Here's a more general technique for left-padding to any desired width:

    declare @x     int     = 123 -- value to be padded
    declare @width int     = 25  -- desired width
    declare @pad   char(1) = '0' -- pad character
    
    select right_justified = replicate(
                               @pad ,
                               @width-len(convert(varchar(100),@x))
                               )
                           + convert(varchar(100),@x)
    

    However, if you're dealing with negative values, and padding with leading zeroes, neither this, nor other suggested technique will work. You'll get something that looks like this:

    00-123
    

    [Probably not what you wanted]

    So … you'll have to jump through some additional hoops Here's one approach that will properly format negative numbers:

    declare @x     float   = -1.234
    declare @width int     = 20
    declare @pad   char(1) = '0'
    
    select right_justified = stuff(
             convert(varchar(99),@x) ,                            -- source string (converted from numeric value)
             case when @x < 0 then 2 else 1 end ,                 -- insert position
             0 ,                                                  -- count of characters to remove from source string
             replicate(@pad,@width-len(convert(varchar(99),@x)) ) -- text to be inserted
             )
    

    One should note that the convert() calls should specify an [n]varchar of sufficient length to hold the converted result with truncation.

    0 讨论(0)
  • 2020-11-22 08:33

    Try this with fixed length.

    select right('000000'+'123',5)
    
    select REPLICATE('0', 5 - LEN(123)) + '123'
    
    0 讨论(0)
提交回复
热议问题