sql减去日期

时间:2011-07-01 13:25:01

标签: sql sql-server

日期列中的某些日期记录错误。如果日期在特定日期范围内,我想提出一个从每个日期减去一天的查询。

我知道我必须使用DATEADD和UPDATE,但我似乎无法弄明白。提前谢谢。

4 个答案:

答案 0 :(得分:4)

这应该这样做:

UPDATE  [SomeTable]
SET     [DateColumn] = DATEADD(d, -1, [DateColumn])
WHERE   [DateColumn] BETWEEN [Date1] AND [Date2]

以下是DATEADD函数中的MSDN文档:http://msdn.microsoft.com/en-us/library/ms186819.aspx

在对此类数据执行更新时,最好使用相同的条件运行选择语句 first ,以确保您更新正确的记录。它还有助于降低更新的压力水平(特别是如果您不熟悉SQL)。

SELECT    *, --Depending on what columns you would like to see, the wildcard could be replaced
          DATEADD(d, -1, [DateColumn]) AS ProposedDate
FROM      [SomeTable]
WHERE     [DateColumn] BETWEEN [Date1] AND [Date2]

答案 1 :(得分:0)

DECLARE @min_date datetime, @max_date datetime;

UPDATE yourtable
SET date_column = DATEADD(day, -1, date_column)
WHERE id IN (
  SELECT id
  FROM yourtable
  WHERE date_column BETWEEN @min_date AND @max_date
);

您必须为@min_date@max_date设置适当的值。

答案 2 :(得分:0)

UPDATE MyTable
SET DateField = DATEADD(Day, -1, DateField)
WHERE Datefield BETWEEN '1/1/2011' AND '2/1/2011'

答案 3 :(得分:0)

use UPDATE
set the data = ( do the date math )
WHERE the date is in the range you want
and the key is the row you want.