zero left (LPAD) on Sql Server

3

How to do in SqlServer so that the result comes with zero left?

In mysql it would look like this:

select lpad(mes,2,0 ) as 'mes', ano from tab_qualquer;

How do you do something equivalent on Sql Server?

I've already searched the link and I did so:

select distinct
     right(replicate('0',2) + mes,2) as mes, 
     ano
from tabela

and gave the following error:

  

Error code 0, SQL state 22019: Unrecognized SQL escape 'year' at line position 702.   Line 1, column 1

    
asked by anonymous 09.03.2016 / 14:16

3 answers

6

If the month field is numeric, to display with leading zero, you must show it as a string. The Error may be masking the real problem. Pass the table structure.

select distinct
     right(replicate('0',2) + convert(VARCHAR,mes),2) as mes, 
     ano
from tabela
    
09.03.2016 / 14:54
1

SEGUE:

Select REPLICATE('0', 2 - LEN(PER_CODIGO)) + RTrim(PER_CODIGO) FROM PERFIL
  • '0' is the character you want to repeat,

  • 2 is the number of houses in your string,

  • 'PER_CODIGO' is your field.

09.03.2016 / 14:55
0

If you want the example below works great.

select RIGHT('000' + CAST('025' AS VARCHAR(10)),8) 
    
04.01.2017 / 16:10