SQL Server date comparisons based on month and year only

后端 未结 6 960
南方客
南方客 2021-02-05 06:27

I am having trouble determining the best way to compare dates in SQL based on month and year only.

We do calculations based on dates and since billing occurs on a monthl

6条回答
  •  鱼传尺愫
    2021-02-05 07:32

    To handle inequalities, such as between, I like to convert date/times to a YYYYMM representation, either as a string or an integer. For this example:

    DECLARE @date1 DATETIME = CAST('6/14/2014' AS DATETIME),
            @date2 DATETIME = CAST('6/15/2014' AS DATETIME),
            @date3 DATETIME = CAST('7/1/2014' AS DATETIME);
    
    SELECT * FROM tableName WHERE @date2 BETWEEN @date1 AND @date3;
    

    I would write the query as:

    SELECT *
    FROM tableName
    WHERE year(@date2) * 100 + month(@date2) BETWEEN year(@date1) * 100 + month(@date1) AND
                                                     year(@date3) * 100 + month(@date1);
    

提交回复
热议问题