0

I'm trying to find the most elegant means of defaulting a column's value to the 1st of next month. The best I've been able to come up with is this:

ALTER TABLE Foo ADD
Bar datetimeoffset(0) NOT NULL DEFAULT(DATEFROMPARTS(DATEPART(year, DATEADD(month, 1, GETDATE())), DATEPART(month, DATEADD(month, 1, GETDATE())), 1))

Whilst this works, it feels really clunky because I need to calculate DATEADD(month, 1, GETDATE()) twice and because I need to do the DATEFROMPARTS dance.

Is there a simpler way to achieve my goal?

4
  • FinalDate = CURRENT_DATE - DAY(CURRENT_DATE) + 1 DAY + 1 MONTH
    – Akina
    Jul 18, 2019 at 5:12
  • @Akina Sure, but when you convert that to a compilable expression it still ends up very unwieldy...
    – me--
    Jul 18, 2019 at 5:17
  • What's the point of saving bytes of query text? Well, use DATEFROMPARTS(YEAR(GETDATE())+(MONTH(GETDATE())/12), 1+(MONTH(GETDATE())%12), 1)
    – Akina
    Jul 18, 2019 at 5:28
  • The point is readability/not wasting developer time, not "saving bytes"
    – me--
    Jul 18, 2019 at 11:09

1 Answer 1

2

It think this would be the simplest way to do it.

DATEADD(DD,1,EOMONTH (GETDATE()))

So you query would be like

ALTER TABLE Foo ADD
Bar datetimeoffset(0) NOT NULL DATEADD(DD,1,EOMONTH (GETDATE()));

Thanks!

1
  • Interesting - thanks! I'll try this out ASAP.
    – me--
    Jul 18, 2019 at 11:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.