Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

LPAD and RPAD Functions in SQL

0.00/5 (No votes)
15 Mar 2012CPOL 10.8K  
This is an alternative for LPAD and RPAD functions in SQL

This way is very simple, but it doesn't protect against the source value being longer than the specified length and it doesn't account for trailing SPACEs in the source value.

SQL
DECLARE @W INTEGER -- Width for result
SET @W = 10

DECLARE @X NVARCHAR(MAX) -- Value to pad
SET @X = 'VALUE'

DECLARE @Y NVARCHAR(MAX) -- Pad character
SET @Y = '#'

DECLARE @Z NVARCHAR(MAX) -- Result
SET @Z = @X + REPLICATE(@Y,@W-LEN(@X)) -- Right pad

SET @Z = REPLICATE(@Y,@W-LEN(@X)) + @X -- Left pad

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)