Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: compare dates by only matching month and day

I have a stored procedure that fetches records based on dates matching a date input which works fine so far. Both the dates in the table and my input date are formatted as datetime.

Instead of comparing the full dates I would like to change this so that it only compares month and day so that it works with any year for the input.

Example: A date in the table is saved as 2013-04-30 and my input date is 2014-04-30. What I want is that the stored procedure still returns that record independent of the year as long as month and day match.

My stored procedure:

ALTER PROCEDURE [dbo].[FetchDays]
    @inputDate datetime
AS
BEGIN
    SET NOCOUNT ON;
    SELECT      dateID,
                dayDT,
                countries,
                regions
    FROM        DaysDT
    WHERE       dayDT = @inputDate
    FOR XML PATH('daysFixed'), ELEMENTS, TYPE, ROOT('root')

END

Many thanks for any help with this, Mike.

like image 304
Mike Avatar asked Apr 26 '14 17:04

Mike


People also ask

How can I compare two dates in SQL Server?

To find the difference between dates, use the DATEDIFF(datepart, startdate, enddate) function. The datepart argument defines the part of the date/datetime in which you'd like to express the difference. Its value can be year , quarter , month , day , minute , etc.

Can we use like operator on date?

Solution 1. Like operator will not work with DateTime.


1 Answers

You can do something like this ;)

ALTER PROCEDURE [dbo].[FetchDays]
    @inputDate datetime
AS
BEGIN
    SET NOCOUNT ON;
    SELECT      dateID,
                dayDT,
                countries,
                regions
    FROM        DaysDT
    WHERE       
        DAY(dayDT) = DAY(@inputDate) --Extract and compare day
        AND MONTH(dayDT) = MONTH(@inputDate) --Extract and compare month
    FOR XML PATH('daysFixed'), ELEMENTS, TYPE, ROOT('root')

END
like image 111
Ryx5 Avatar answered Oct 04 '22 10:10

Ryx5