如何在一月份使用 MSSQL 获取上个月间隔

How to get Last Month interval with MSSQL in January

如何修复此代码,使其在 1 月份不中断?我认为这部分是错误:

(Month(Getdate()) - 1

SQL:

AND UOnline.maxstamp > dbo.Udf_converttotimeinterval(
                           Cast(Cast(Year(Getdate()) AS VARCHAR(4))
                           + RIGHT('0' + Cast((Month(Getdate()) - 1) AS VARCHAR(2)), 2)
                           + RIGHT('0' + Cast(1 AS VARCHAR(2)), 2) AS DATETIME), 'ss')

AND UOnline.maxstamp < dbo.Udf_converttotimeinterval(
                           Cast(Cast(Year(Getdate()) AS VARCHAR(4))
                           + RIGHT('0' + Cast(Month(Getdate()) AS VARCHAR(2)), 2)
                           + RIGHT('0' + Cast(1 AS VARCHAR(2)), 2) AS DATETIME), 'ss')

用户自定义函数,如果有人需要的话:

USE [XXX]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/**** UDF_ConvertToTimeInterval ****/
ALTER FUNCTION [dbo].[UDF_ConvertToTimeInterval](@VALUE DATETIME, 
@INVERVALTYPE VARCHAR(2))
RETURNS BIGINT WITH SCHEMABINDING AS 
BEGIN
    IF @INVERVALTYPE IS NOT NULL
        Begin           
            If Upper(@INVERVALTYPE) = 'S' OR Upper(@INVERVALTYPE) = 'SS'
                RETURN DATEDIFF(SECOND, CONVERT(DATETIME, '01/01/1970', 101), 
                                        CONVERT(DATETIME, @VALUE, 101))
            If Upper(@INVERVALTYPE) = 'MI' OR Upper(@INVERVALTYPE) = 'N'
                RETURN DATEDIFF(MINUTE, CONVERT(DATETIME, '01/01/1970', 101), 
                                        CONVERT(DATETIME, @VALUE, 101))
            If Upper(@INVERVALTYPE) = 'H' OR Upper(@INVERVALTYPE) = 'HH'
                RETURN DATEDIFF(HOUR, CONVERT(DATETIME, '01/01/1970', 101), 
                                      CONVERT(DATETIME, @VALUE, 101))
            If Upper(@INVERVALTYPE) = 'D' OR Upper(@INVERVALTYPE) = 'DD'
                RETURN DATEDIFF(DAY, CONVERT(DATETIME, '01/01/1970', 101), 
                                     CONVERT(DATETIME, @VALUE, 101))
            If Upper(@INVERVALTYPE) = 'M' OR Upper(@INVERVALTYPE) = 'MM'
                RETURN DATEDIFF(MONTH, CONVERT(DATETIME, '01/01/1970', 101), 
                                       CONVERT(DATETIME, @VALUE, 101))
            If Upper(@INVERVALTYPE) = 'Y' OR Upper(@INVERVALTYPE) = 'YY'
                RETURN DATEDIFF(YEAR, CONVERT(DATETIME, '01/01/1970', 101), 
                                      CONVERT(DATETIME, @VALUE, 101))
            Else
                Return Null
        end     
    Else
        Return null
    Return null
END

简化月/日的减法通常不是一个好主意...而不是

(Month(Getdate()) - 1

试试下面的方法

MONTH(DATEADD(MONTH, -1, GETDATE()))