SQL Server:如何在每个日历月结束时运行存储过程

SQL Server:如何在每个日历月结束时运行存储过程,sql,sql-server,tsql,Sql,Sql Server,Tsql,我需要在每个日历月底执行一个存储过程。应以本月底为结束日期,以上个月底为开始日期 这里有一些例子: exec my_report @ReportStartDate = '20140731', @ReportEndDate='20140831' exec my_report @ReportStartDate = '20140131', @ReportEndDate='20131231' exec my_report @ReportStartDate = '20140228', @ReportEnd

我需要在每个日历月底执行一个存储过程。应以本月底为结束日期,以上个月底为开始日期

这里有一些例子:

exec my_report @ReportStartDate = '20140731', @ReportEndDate='20140831'
exec my_report @ReportStartDate = '20140131', @ReportEndDate='20131231'
exec my_report @ReportStartDate = '20140228', @ReportEndDate='20140131'
我的目标是将结果存储在表中。所以我需要创建一个新的存储过程来调用当前的存储过程

我找不到调度
my_report
存储过程的方法。所以我创建了一个新的存储过程。我的目标是每天调用
caller\u sp
,并检查caller存储过程中的日期

这里是我的调用者存储过程。我对oracle有很好的了解,但我对SQL Server不熟悉

  • 是否有办法在每个日历月底安排我的报告,并发送开始和结束日期
  • 下面有我的代码的合适版本吗
  • 代码:


    你可以简化很多

    如果您使用的是现代SQL Server,则可以使用
    EOMONTH
    函数获取当月的最后一天

    如果您的SQL Server较旧,您可以使用一个小技巧:使用
    DATEADD
    函数在当前deta中添加1天(
    getdate()
    ),并比较月份(使用
    month
    函数)。如果是同一个月,那就不是这个月的最后一天。如果是不同的月份,那是因为这是一个月的最后一天

    参考资料:


      • 您的脚本似乎有点复杂

        DECLARE @ReportStartDate date, @ReportEndDate date
        
        -- for sqlserver 2012
        SELECT 
          @ReportStartDate = EOmonth(getdate(), -1),
          @ReportEndDate = EOmonth(getdate())
        
        -- for earlier versions
        SELECT 
          @ReportStartDate = dateadd(month, datediff(m, 0, getdate()), -1),
          @ReportEndDate =  dateadd(month, datediff(m, -1, getdate()), -1)
        
        EXEC my_report @ReportStartDate, @ReportEndDate
        
        要在每个月的最后一天执行作业:

        创建一个作业,然后查找并选择

        欠频:

        发生时间:每月
        每1个月的最后一天

        这里是我的脚本。我换了一个SP。它很好用。谢谢大家

        declare
        @ReportStartDate DATETIME=EOmonth(getdate(), -1),
        @ReportEndDate DATETIME=EOmonth(getdate())
        
        if @ReportEndDate=getdate()
        Begin
        
        insert into report_log (col1,
        col2,
        col3
        ) exec Report @ReportStartDate, @ReportEndDate,@username=null,@LanguageId=null
        
        update report_log set reportstartdate=@ReportStartDate, reportenddate=@ReportEndDate  where reportenddate is null
        end 
        

        这个问题我肯定要迟到了,我可能会断章取义地发布答案。但正如@JotaBe所说(在我的例子中是旧版本),你可以通过这种简单的方式知道你是否在新的月份(如果你有运行第1个月报告的脚本)

        declare @cDate as date = getDate(), @comDate as Date;
        set @comDate = DATEADD(day, -1, @cDate)
        if DATEPART(MONTH, @cDate) > DATEPART(month, @comDate)
            print 'Different month'
        else
            print 'same month'
        
        如果你可以微调到你想要的任何东西(作业步骤等),那么在

        declare @cDate as date = getDate(), @comDate as Date;
        set @comDate = DATEADD(day, -1, @cDate)
        if DATEPART(MONTH, @cDate) > DATEPART(month, @comDate)
            print 'Different month'
        else
            print 'same month'