Thursday, August 11, 2011

SQL Server: LPAD Function

CREATE FUNCTION [dbo].[LPAD](@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

0 comments:

Post a Comment