增加dateadd的计数器

时间:2010-09-06 08:54:18

标签: sql sql-server sql-server-2005 tsql

我正在尝试将日期之间的时间增加一定数量。例如,我想在日期1,2和3之间添加两个月。我无法增加我的'日期计数器'......

DECLARE @monthDiff int

SET @monthDiff = 1;

UPDATE [Table1]
SET [Date] = DATEADD(MONTH, (SET @monthDiff = @monthDiff + 1), [Date])
WHERE [ID] IN 
(
    SELECT [ID]
    FROM [Table2]
    WHERE [Description] = 'HE'
);

一个例子可能有帮助...

原始日期:

01/04/1984
01/05/1984
01/06/1984

新日期:

01/04/1984
01/06/1984
01/08/1984

有什么想法吗?

我正在使用SQLServer 2005。

感谢。

3 个答案:

答案 0 :(得分:1)

;WITH cte AS
(
SELECT t1.ID, 
       t1.[Date], 
       ROW_NUMBER() OVER (PARTITION BY t1.ID ORDER BY [Date]) AS RN
FROM Table1 t1
JOIN Table2 t2
ON t1.ID = t2.ID 
WHERE t2.[Description] = 'HE'
)
UPDATE CTE
SET [Date] = DATEADD(MONTH, RN-1, [Date])

答案 1 :(得分:0)

这应该可行,但前提是表中的每个原始日期都是唯一的。我已经调用了列mydate,因为我认为date不是列的合法(或合理)名称。如果您有某种ID列,这可能会更容易,更安全。然后我们将其用于光标而不是日期

declare @numberOfMonthsToAdd int
declare @currentDate dateTime
set @numberOfMonthsToAdd = 0
declare myCursor cursor  for 
select [mydate] from Table1
open myCursor
while @@fetch_Status<>-1
begin
fetch next from myCursor into @currentDate
update Table1 set [mydate] = DATEADD(month,@numberOfMonthsToAdd, [mydate]) where [mydate] = @currentDate
set @numberOfMonthsToAdd = @numberOfMonthsToAdd + 1

end
close mycursor
deallocate mycursor

答案 2 :(得分:0)

从您的示例中,您似乎想要更改相对于基准日期的日期:

declare @basedate datetime
select @basedate = min([Date]) FROM Table1 WHERE ...

UPDATE [Table1]
SET [Date] = DATEADD(MONTH, DATEDIFF(MONTH, @basedate, [Date]) * 2, [Date])
WHERE ...