65.9K
CodeProject is changing. Read more.
Home

LPAD and RPAD Functions in SQL

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Mar 15, 2012

CPOL
viewsIcon

10760

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.

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