Skip to content

Instantly share code, notes, and snippets.

@craibuc
Last active December 30, 2015 10:19
Show Gist options
  • Select an option

  • Save craibuc/7815502 to your computer and use it in GitHub Desktop.

Select an option

Save craibuc/7815502 to your computer and use it in GitHub Desktop.
Useful, dynamically-generated dates for SQL Server.
--[1st day of current month]: use the GetDate(), Month(), and Year() functions to determine the current month and year. Build a string using these values in MM/01/YYYY format. Convert the String to DateTime.
CAST( CAST( Month(GetDate()) AS Char(2) ) + '/01/' + CAST( Year(GetDate()) AS Char(4)) AS DateTime)
--[Last day of current month]: add a month to [1st day of current month], then subtract a day.
DateAdd(m, 1, CAST( CAST( Month(GetDate()) AS Char(2) ) + '/01/' + CAST( Year(GetDate()) AS Char(4)) AS DateTime)) -1
--[1st day of prior month]: subtract a month from [1st day of current month].
DateAdd(m, -1, CAST( CAST( Month(GetDate()) AS Char(2) ) + '/01/' + CAST( Year(GetDate()) AS Char(4)) AS DateTime))
--[Last day of prior month]: subtract a day from [1st day of current month].
CAST( CAST( Month(GetDate()) AS Char(2) ) + '/01/' + CAST( Year(GetDate()) AS Char(4)) AS DateTime) -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment