PadLeft function in T-SQL

后端 未结 17 2827
挽巷
挽巷 2020-11-27 03:44

I have the following table A:

id
----
1
2
12
123
1234

I need to left-pad the id values with zero\'s:

id
----
0         


        
17条回答
  •  情深已故
    2020-11-27 04:16

    I created a function:

    CREATE FUNCTION [dbo].[fnPadLeft](@int int, @Length tinyint)
    RETURNS varchar(255) 
    AS 
    BEGIN
        DECLARE @strInt varchar(255)
    
        SET @strInt = CAST(@int as varchar(255))
        RETURN (REPLICATE('0', (@Length - LEN(@strInt))) + @strInt);
    END;
    

    Use: select dbo.fnPadLeft(123, 10)

    Returns: 0000000123

提交回复
热议问题