Sunday, March 25, 2012

Adding a leading character to a string

I'm looking for a string function (or any other quick way) for adding a leading zero to make a string two characters long. For example, if the input is '12' the result will be '12' but if the input is '1', the result will be '01'.

It's actually about making a month number two characters long but I've understood there is no way to make Datediff() to fix it for me.

I thought there might be a string function for this, like there is in many programming languages, but I can't find anything in BOL. I want to keep it simple, because it will be used in a Select and a Group By for aggregating data based on time intervals (year + month).

And, I assume I can't make Datepart() to return year + month directly, only one of the parts at a time.SELECT Convert(CHAR(7), GetDate(), 121)
Use the date expresion of your choice instead of GetDate()

-PatP|||I use this ;)

create function dbo.FN_INT_TOSTRING(@.codigo int, @.length int) returns varchar(10)
begin
declare @.res varchar(10)
set @.res = cast(@.codigo as varchar)
while len(@.res) < @.length
begin
set @.res = '0' + @.res
end
return @.res
end|||What about a generic function like:

Right('0' + cast(@.MyInt as varchar(2)), 2)

But Pat really has the best answer here.

Regards,

hmscott|||Thanks everyone. Simpler than I first thought! I'll play with it at work on Monday morning (9 PM over here now).

PS. Sorry for replying from another alias - I now realize I'm logged on as Coolberg from my work and as Nabucco from my home computer. I'll correct that. ;-)
DS.|||So finding an answer at 21:00 on Friday night doesn't inspire you to run right down to the office to try it ? Well, what kind of geek are you anyway ? Next thing you know, you'll be telling us that you're going to enjoy a cold beer and a warm bed!

-PatP|||select convert(varchar(2),getdate(),101)|||> Next thing you know, you'll be telling us that you're going to enjoy a cold beer and a warm bed!

I missed the beer; the beer shop here closes at 6 PM ;-)|||select convert(varchar(2),getdate(),101)

I'll test this one tomorrow.

By the way, SELECT Convert(CHAR(7), GetDate(), 121) didn't work.

I tried Right('0' + cast(@.MyInt as varchar(2)), 2) today, it worked fine.|||waddyamean it didn't work...of course it worked...read the hint sticky at the top of the forum|||The problem is, I'm doing a (for example)

select convert(varchar(2),datepart(mm,'2006-01-30'),101)

where you'll still get "1" since datepart() returns "1" , not "01".|||select right(convert(char(7),yourdate,120),2)|||And, I assume I can't make Datepart() to return year + month directly, only one of the parts at a time.select convert(char(7),yourdate,120)|||Select convert(varchar(2),convert(datetime,'2006-01-30'),101)|||Thanks everybody!

No comments:

Post a Comment