Prefix a string with a specified character to pad it to a desired length
1 2 CREATE FUNCTION dbo.f_pad_before(@string VARCHAR(255), @desired_length INTEGER, @pad_character CHAR(1)) 3 RETURNS VARCHAR(255) AS 4 BEGIN 5 6 -- Prefix the required number of spaces to bulk up the string and then replace the spaces with the desired character 7 RETURN CASE 8 WHEN LEN(@string) < @desired_length 9 THEN REPLACE(SPACE(@desired_length - LEN(@string)), ' ', @pad_character) + @string 10 ELSE @string 11 END 12 13 END 14 GO
Example of usage:
1 2 SELECT dbo.f_pad_before('my string', 20, '-') AS [result], LEN(dbo.f_pad_before('my string', 20, '-')) AS [length]