简体   繁体   中英

How to see if date is in current month SQL Server?

I have a Ticket_Date column that is in the format YYYY-MM-DD HH:MI:SS

I want to check if the Ticket_date is in the current month.

So far I have :

 Ticket_date >= '2015-04-01' and Ticket_date < '2015-04-30'

but I need it to work with the current month rather then hardcoded

 YEAR(Ticket_date) = YEAR(getdate()) and 
MONTH(Ticket_date) = MONTH(getdate())

but i would also save current date in variable to guarantee what result of getdate() doesn't change when executing long query at midnight

declare @today datetime = getdate()
...
 YEAR(Ticket_date) = YEAR(@today) and 
MONTH(Ticket_date) = MONTH(@today)
MONTH(Ticket_date) = MONTH(GETDATE()) AND YEAR(Ticket_date) = YEAR(GETDATE())

How about this?

where ticket_date >= cast(getdate() - day(getdate) + 1 as date) and
      ticket_date < dateadd(month, 1, cast(getdate() - day(getdate) + 1 as date) )

This formulation has no functions on ticket_date , so SQL Server can use an index on the column, if appropriate.

What about (Server 2008 R2+)

-- first day of current month
Ticket_date  >= DATEADD(m, DATEDIFF(m, 0, GETDATE()), 0)
-- last day of current month 
and Ticket_date <= DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) 

More examples here How can I select the first day of a month in SQL?

  • Why do you omit the = in Ticket_date < '2015-04-30' ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM