Results 1 to 5 of 5

Thread: SQL 2005 getting month as two digits [resolved]

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    262

    Resolved SQL 2005 getting month as two digits [resolved]

    Hi All,

    For a quite convoluted reason I need to bulid a string which contains the month as two digits. I came up with the following sql statement
    Code:
    declare @month int
    set @month = (select cast(datepart(m,getdate()) as integer))
    declare @lmonth varchar(2)
    set @lmonth =  CASE 
             WHEN  @month <10   THEN '0' + cast(@month as varchar)
             ELSE cast(@month as varchar)
          END
    select @lmonth
    But seems to me there must be a much much sleaker way to achive the same thing, any help would be appreciated.
    Last edited by Oliver1; Jul 7th, 2009 at 07:53 AM. Reason: Resolved

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: SQL 2005 getting month as two digits

    How about this?
    Code:
    select right('0' + cast(datepart(m,getdate()) as varchar(2)),2))
    If that doesn't work, which database system are you using?

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    262

    Re: SQL 2005 getting month as two digits

    Thanks that does work and cuts down on the code quite considerably.

  4. #4
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: SQL 2005 getting month as two digits [resolved]

    As you now have it sorted out, could you please do us a little favour, and mark the thread as Resolved?
    (this saves time reading for those of us who like to answer questions, and also helps those who search to find answers)

    You can do it by clicking on "Thread tools" just above the first post in this thread, then "Mark thread resolved". (like various other features of this site, you need JavaScript enabled in your browser for this to work).


    edit: sorry, I see you've done it manually (but with Resolved at the end of the thread title rather than the start)

  5. #5

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    262

    Re: SQL 2005 getting month as two digits [resolved]

    Have learnt something else now, didn't realise you could resolve a thread automatically using thread tools. Will remember for next time.
    Thanks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width