WHERE Clause to find all records in a specific month

后端 未结 10 2133
傲寒
傲寒 2020-12-04 10:07

I want to be able to give a stored procedure a Month and Year and have it return everything that happens in that month, how do I do this as I can\'t compare between as some

10条回答
  •  感动是毒
    2020-12-04 10:38

    Using the MONTH and YEAR functions as suggested in most of the responses has the disadvantage that SQL Server will not be able to use any index there may be on your date column. This can kill performance on a large table.

    I would be inclined to pass a DATETIME value (e.g. @StartDate) to the stored procedure which represents the first day of the month you are interested in.

    You can then use

    SELECT ... FROM ...
    WHERE DateColumn >= @StartDate 
    AND DateColumn < DATEADD(month, 1, @StartDate)
    

    If you must pass the month and year as separate parameters to the stored procedure, you can generate a DATETIME representing the first day of the month using CAST and CONVERT then proceed as above. If you do this I would recommend writing a function that generates a DATETIME from integer year, month, day values, e.g. the following from a SQL Server blog.

    create function Date(@Year int, @Month int, @Day int)
    returns datetime
    as
        begin
        return dateadd(month,((@Year-1900)*12)+@Month-1,@Day-1)
        end
    go
    

    The query then becomes:

    SELECT ... FROM ...
    WHERE DateColumn >= Date(@Year,@Month,1)
    AND DateColumn < DATEADD(month, 1, Date(@Year,@Month,1))
    

提交回复
热议问题