更新每条记录的日期

时间:2015-10-20 17:55:24

标签: sql-server tsql cursor

我正在尝试这样的事情

 DECLARE @CreateDate DATETIME, @iCount BIGINT
 SET @iCount=0
 SET @CreateDate=DATEADD(s,.5,GETDATE()) 
 DECLARE iCreateDate CURSOR FOR
 SELECT ID
 FROM Table AS 
 WHERE CreateDate IS null ;
 OPEN iCreateDate ;
 FETCH FROM iCreateDate ;
 UPDATE Table
 SET CreateDate = @CreateDate
 WHERE CURRENT OF iCreateDate ;
 SET @iCount=@iCount+1
 WAITFOR DELAY '00:00:00.5';
 WHILE     (SELECT COUNT(ID)
 FROM Table AS 
 WHERE CreateDate IS NULL) > 0
 FETCH NEXT FROM iCreateDate INTO @CreateDate

 CLOSE iCreateDate ;
 DEALLOCATE iCreateDate ;
GO

1 个答案:

答案 0 :(得分:1)

您可以利用CTE为每个行生成行号,并将其用作时间增量的乘数。

WITH cteNullDates AS (
    SELECT ID, 
           CreateDate,
           ROW_NUMBER() OVER (ORDER BY ID) AS RowNum
        FROM Table
        WHERE CreateDate IS NULL
)
UPDATE cteNullDates
    SET CreateDate = DATEADD(MILLISECOND, RowNum * 500, GETDATE());