相比之下,说:

REPLICATE(@padchar, @len - LEN(@str)) + @str

当前回答

可能有点夸张,我经常使用这个UDF:

CREATE FUNCTION [dbo].[f_pad_before](@string VARCHAR(255), @desired_length INTEGER, @pad_character CHAR(1))
RETURNS VARCHAR(255) AS  
BEGIN

-- Prefix the required number of spaces to bulk up the string and then replace the spaces with the desired character
 RETURN ltrim(rtrim(
        CASE
          WHEN LEN(@string) < @desired_length
            THEN REPLACE(SPACE(@desired_length - LEN(@string)), ' ', @pad_character) + @string
          ELSE @string
        END
        ))
END

这样你就可以做这样的事情:

select dbo.f_pad_before('aaa', 10, '_')

其他回答

有几个人给出了不同的版本:

right('XXXXXXXXXXXX'+ @str, @n)

要小心,因为如果它比n长,它会截断实际数据。

在SQL Server 2005及以后的版本中,您可以创建一个CLR函数来完成此操作。

我用这个。它允许您确定想要的结果长度,以及如果没有提供默认填充字符。当然,您可以为遇到的任何最大值定制输入和输出的长度。

/*===============================================================
 Author         : Joey Morgan
 Create date    : November 1, 2012
 Description    : Pads the string @MyStr with the character in 
                : @PadChar so all results have the same length
 ================================================================*/
 CREATE FUNCTION [dbo].[svfn_AMS_PAD_STRING]
        (
         @MyStr VARCHAR(25),
         @LENGTH INT,
         @PadChar CHAR(1) = NULL
        )
RETURNS VARCHAR(25)
 AS 
      BEGIN
        SET @PadChar = ISNULL(@PadChar, '0');
        DECLARE @Result VARCHAR(25);
        SELECT
            @Result = RIGHT(SUBSTRING(REPLICATE('0', @LENGTH), 1,
                                      (@LENGTH + 1) - LEN(RTRIM(@MyStr)))
                            + RTRIM(@MyStr), @LENGTH)

        RETURN @Result

      END

你的里程可能会有所不同。: -) 乔伊摩根 一级程序设计/分析主任 WellPoint医疗补助事业单位

我希望这能帮助到一些人。

STUFF ( character_expression , start , length ,character_expression )

select stuff(@str, 1, 0, replicate('0', @n - len(@str)))
select right(replicate(@padchar, @len) + @str, @len)