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

后端 未结 17 1284
清歌不尽
清歌不尽 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条回答
  •  猫巷女王i
    2020-11-22 08:35

    Wrote this because I had requirements for up to a specific length (9). Pads the left with the @pattern ONLY when the input needs padding. Should always return length defined in @pattern.

    declare @charInput as char(50) = 'input'
    
    --always handle NULL :)
    set @charInput = isnull(@charInput,'')
    
    declare @actualLength as int = len(@charInput)
    
    declare @pattern as char(50) = '123456789'
    declare @prefLength as int = len(@pattern)
    
    if @prefLength > @actualLength
        select Left(Left(@pattern, @prefLength-@actualLength) + @charInput, @prefLength)
    else
        select @charInput
    

    Returns 1234input

提交回复
热议问题