Thursday, March 22, 2012

Converting 7 (int) to 07 (varchar)

Hi,

I'm converting a query from Access to SQL Server.

In this query I select from a column that contains numbers, the result I want is a varchar that is always 2 chars wide..

Ie:
7 should be selected as '07'
12 should be selected as '12'

In the Access-query it's rather nicely done with:
Format(Str(mycolumn),"00")

I could not find a way to make CONVERT do the same job... but I found that:
LEFT('00',2-LEN(CAST(mycolumn as varchar)))+CAST(mycolumn as varchar)
will do the job.

But it feels like it could be done nicer.. any suggestions?Im Pretty new to this myself but how about

RIGHT('00' + CAST(MyColumn as Varchar(2)),2)

Dave|||Thanks, I was too left oriented in my thinking :-)

No comments:

Post a Comment