LPAD in SQL Server 2008

后端 未结 4 1623
梦谈多话
梦谈多话 2020-11-30 07:40

I can\'t see a function like LPAD in SQL Server 2008. For example how can I convert the following queries into T-SQL?

select  LPAD(MY_VALUE,2,\'          


        
4条回答
  •  失恋的感觉
    2020-11-30 07:54

    I've come up with a LPAD and RPAD function where you can use a characterstring for the pad-part.

    They should work the same as the DB2 versions.

    Here's the LPAD:

    CREATE FUNCTION dbo.LPAD
    (
        @string NVARCHAR(MAX), -- Initial string
        @length INT,           -- Size of final string
        @pad NVARCHAR(MAX)     -- Pad string
    )
    RETURNS VARCHAR(MAX)
    AS
    BEGIN
        RETURN SUBSTRING(REPLICATE(@pad, @length),1,@length - LEN(@string)) + @string;
    END
    GO
    

    And here is the RPAD:

    CREATE FUNCTION dbo.RPAD
    (
        @string NVARCHAR(MAX), -- Initial string
        @length INT,           -- Size of final string
        @pad NVARCHAR(MAX)     -- Pad string
    )
    RETURNS VARCHAR(MAX)
    AS
    BEGIN
        RETURN @string + SUBSTRING(REPLICATE(@pad, @length),1,@length - LEN(@string));
    END
    GO
    

提交回复
热议问题