What are the challenges you face when working across database platforms? Take the survey

Start date of the current month

Brian DonahueBrian Donahue Posts: 6,590 Bronze 1
edited March 1, 2012 12:49PM in SQL Prompt code snippets
Here is a bit of code I have grown tired of typing over and over again. It returns a string describing the date for the start of the current month, for instance '20080301'.


  • Options
    How about this?

    select convert(nvarchar(8),dateadd(mm, datediff(mm, 0, getdate()), 0), 112) -- first day of month
  • Options
    Brian DonahueBrian Donahue Posts: 6,590 Bronze 1
    Thanks, this is much more succinct than the original!
  • Options
    EdCardenEdCarden Posts: 137 Silver 2

    If you're finding that you need to get the first of the month often then you could look at incorporating a Lookup table into your coide that consist of rows for each date that falls within a range that would cover the dates you'd expect to use for the next 5 yeras or so. The table would include the Date, the first day of that month, the last day of that month as well as other Date related data that is often obtained using one of the t-sql date functions and or string functions.

    I work in a date heavy industry in which our transactional table has hundreads of millions of rows. More then %50 of the queries involved need to get the first day of whatever month/Year the date on the transaction falls within. Instead of using some extensive combination of string and date functions I join to a date lookup table on the date and return from it that First day of the month value. Its very handy to have.
Sign In or Register to comment.