Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LPAD in SQL Server 2008

I can't see a function like LPAD in SQL Server 2008. For example how can I convert the following queries into T-SQL?

select  LPAD(MY_VALUE,2,' ')) VALUE FROM MY_TABLE 
like image 508
jhash Avatar asked May 06 '11 13:05

jhash


People also ask

What is Lpad command in SQL?

The LPAD() function left-pads a string with another string, to a certain length.

What is Lpad and RPAD in SQL?

LPAD is used to pad the left side of a base string with a given pad string. It will repeat the pad string until the given length is met. RPAD is similar but adds the padding on the right side of the base string.


2 Answers

Basically pad it with the number of characters you are intending to select and then right the string.

Select right(replicate(' ',2) + YourFieldValue,2) from YourTable 

You can use the space function instead of replicate, space(number_of_spaces), replicate just allows you to pad with alternative characters.

like image 62
Andrew Avatar answered Sep 22 '22 11:09

Andrew


Manual calculations can be annoying to apply inside queries. Luckily, we can create a function:

CREATE FUNCTION LPAD (     @string VARCHAR(MAX), -- Initial string     @length INT,          -- Size of final string     @pad CHAR             -- Pad character ) RETURNS VARCHAR(MAX) AS BEGIN     RETURN REPLICATE(@pad, @length - LEN(@string)) + @string; END GO 

(Please replace VARCHAR with NVARCHAR to your liking, or use an alternative algorithm.)

Then:

SELECT dbo.LPAD(MY_VALUE, 2, ' ') VALUE FROM MY_TABLE 

Should work since SQL Server 2005.

like image 31
Álvaro González Avatar answered Sep 20 '22 11:09

Álvaro González