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

时间:2018-01-17 07:00:39

标签: sql-server user-defined-functions sql-date-functions sqldatetime

如何修复此代码,因此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

1 个答案:

答案 0 :(得分:1)

简单地从月/日减去通常是一个坏主意......而不是

(Month(Getdate()) - 1

尝试以下

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