修改自动存储过程日期

时间:2015-09-24 20:58:08

标签: sql-server stored-procedures

我想知道是否有人可以帮助我使用此SQL Server存储过程。每天由SQL Server代理程序根据下面的日期参数获取文档来执行此过程。

    AND DRDateCaptured between '2015-04-15 00:00:01.000' and Getdate()
    AND DRDocumentFileName <> isnull(OriginalDocName,'')

我必须修改查询,以便每次执行时再抓取两天,例如,如果明天执行该作业,它将在今天截至4月12日,第二天将是4/10/15等等。我正在寻找不同的方法来做这个并考虑使用DATEDIFF,但因为我是sql的新手,我不知道如何实现它。任何帮助都非常感谢。

编辑:程序的另一部分我不确定这是否有帮助:

 PartList = dbo.fn_GetClientParts(D.DID, D.DClientDocNumber),
    convert(VARCHAR, d.dbek, 101) AS bekstart,
    convert(VARCHAR, d.dbekendd, 101) AS bekend
    Empty = '||',
    CONVERT(CHAR(10), GetDate(), 101) AS DATE

2 个答案:

答案 0 :(得分:2)

首先,我建议您实施一个辅助日期表,您可以从中进行计算。这将提高您的表现。

其次,如果您要设置日期,则需要对DATEDIFF和DATEADD进行组合。

在您的示例中,您说您希望在某个日期之后的每个日期将日期范围扩展2。在你的例子中,7月31日是关键日期。

距您的关键点的终点之间的距离是3x,其中x是从7月31日到今天的日期的天数。

SELECT
  GETDATE() AS today,
  DATEDIFF( DD, '7/31/2015', GETDATE() ) AS days_from_pivot,
  DATEADD( DD, -3 * DATEDIFF( DD, '7/31/2015', GETDATE() ), GETDATE() ) AS past_target_date

您的情况将是:

DRDateCaptured BETWEEN DATEADD( DD, -3 * DATEDIFF( DD, '7/31/2015', GETDATE() ), GETDATE() ) AND GETDATE()

如果您要删除第一个日期的时间,可以使用以下内容:

DRDateCaptured BETWEEN CONVERT( DATETIME, FLOOR( CONVERT( FLOAT, DATEADD( DAY, -3 * DATEDIFF( DD, '7/31/2015', GETDATE() ), GETDATE() ) ) ) ) AND GETDATE()

如果您想在透视日期的100天内查看其工作原理,可以运行以下查询:

DECLARE @pivot_date DATETIME
SELECT @pivot_date = CONVERT( DATETIME, '7/31/2015' )

SELECT
  CONVERT( DATETIME, FLOOR( CONVERT( FLOAT, DATEADD( DAY, -3 * DATEDIFF( DD, @pivot_date, target_end_date ), target_end_date ) ) ) ) AS start_date,
  target_end_date AS end_date
FROM
  (  
    SELECT
      DATEADD( DAY, iq_a.n * 10 + iq_b.n, @pivot_date ) AS target_end_date
    FROM
      ( SELECT 1 AS n UNION SELECT 2 AS n UNION SELECT 3 AS n UNION SELECT 4 AS n UNION SELECT 5 AS n UNION SELECT 6 AS n UNION SELECT 7 AS n UNION SELECT 8 AS n UNION SELECT 9 AS n UNION SELECT 0 AS n ) AS iq_a,
      ( SELECT 1 AS n UNION SELECT 2 AS n UNION SELECT 3 AS n UNION SELECT 4 AS n UNION SELECT 5 AS n UNION SELECT 6 AS n UNION SELECT 7 AS n UNION SELECT 8 AS n UNION SELECT 9 AS n UNION SELECT 0 AS n ) AS iq_b
  ) AS virtual_auxiliary_date_table
ORDER BY
  target_end_date

希望这有帮助。

答案 1 :(得分:0)

您正在寻找像DATEADD

这样的东西
2 is the days to add..  -2 would give 2 days prior. then use getdate() or the date parameter you need as the last parameter supplied.

select DATEADD(day, 2, getdate())