简体   繁体   中英

What is SQL Server statement to get day and month ignoring the current year?

I have table HD_Case_Master with a column cm_date_created .

The example value is 2011-05-13 10:07:36.000 .

I manage to get the current year but how to get record for all day and month.

SQL statement:

SELECT 
    cm_create_date 
FROM 
    HD_Case_Master 
WHERE
    YEAR(cm_create_date) = YEAR(GETDATE()) AND ???

If you want the current date:

SELECT cm_create_date
FROM HD_Case_Master 
WHERE cm_create_date >= CAST(GETDATE() as date) AND
      cm_create_date < CAST(DATEADD(day, 1, GETDATE()) as date) 

If you want to check if cm_date_created is equal to the current date, ignoring the time component, you just need to CAST both dates to DATE :

SELECT *
FROM HD_Case_Master
WHERE
    CAST(cm_create_date AS DATE) = CAST(GETDATE() AS DATE)

Alternatively, you can use >= and < to check if cm_date_created falls within the current date:

SELECT *
FROM HD_Case_Master
WHERE
    cm_create_date >= CAST(GETDATE() AS DATE)
    AND cm_create_date < CAST(DATEADD(DAY, 1, GETDATE()) AS DATE)

您可以使用tsql的DATEPART函数。

... Where DATEPART(day, cm_create_date) = DATEPART(day, getdate()) AND DATEPART(month, cm_create_date) = DATEPART(month, getdate())

You were really close! To add just the month (but ignoring the year), just use this:

SELECT 
    cm_create_date 
FROM 
    HD_Case_Master 
WHERE
    YEAR(cm_create_date) = YEAR(GETDATE()) 
    AND MONTH(cm_create_date) = MONTH(GETDATE())

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