21

我需要一个用于以下查询的游标,以便我可以循环获取/更新/插入一些其他数据。有人可以帮我吗?

DECLARE @FROMDATE DATETIME
DECLARE @TODATE DATETIME
SELECT @FROMDATE = Getdate()
SELECT @TODATE = Getdate() + 7

;WITH DATEINFO(DATES)
     AS (SELECT @FROMDATE
         UNION ALL
         SELECT DATES + 1
         FROM   DATEINFO
         WHERE  DATES < @TODATE)
SELECT *
FROM   DATEINFO
OPTION (MAXRECURSION 0)

我尝试了很多方法,但没有找到任何有效的方法。

我正在使用

declare @adate datetime
DECLARE @FROMDATE DATETIME 
DECLARE @TODATE DATETIME 
select @FROMDATE=getdate()
select @TODATE =getdate()+7

declare @weekdates cursor for
WITH DATEINFO(DATES) AS (SELECT @FROMDATE UNION ALL SELECT DATES + 1 FROM DATEINFO WHERE DATES < @TODATE) 
SELECT * FROM DATEINFO OPTION (MAXRECURSION 0)

open @weekdates
fetch next from @weekdates into @adate
while @@fetch_status=0
begin
print 'success'
fetch next from @weekdates into @adate
end
close @weekdates
deallocate @weekdates

我仍然遇到错误

4

2 回答 2

39

只需将它放在公用表表达式之前:

DECLARE @FROMDATE DATETIME 
DECLARE @TODATE DATETIME 
select @FROMDATE=getdate()
select @TODATE =getdate()+7

declare boris cursor for

WITH DATEINFO(DATES)
     AS (SELECT @FROMDATE
         UNION ALL
         SELECT DATES + 1
         FROM   DATEINFO
         WHERE  DATES < @TODATE)
SELECT *
FROM   DATEINFO
OPTION (MAXRECURSION 0) 

(但是,插入关于游标几乎总是错误的工作工具的常见警告。如果您能找到一种方法以基于集合的方式完成整个操作,它通常是可取的,并且可能会执行得更好(或至少更多适合性能调整))

于 2013-01-30T10:20:00.713 回答
20

可以@在游标名称中使用,但您使用的语法是错误的。

DECLARE @adate DATETIME
DECLARE @FROMDATE DATETIME
DECLARE @TODATE DATETIME

SELECT @FROMDATE = getdate()

SELECT @TODATE = getdate() + 7

DECLARE @weekdates CURSOR;

SET @weekdates = CURSOR FOR
WITH DATEINFO(DATES)
     AS (SELECT @FROMDATE
         UNION ALL
         SELECT DATES + 1
         FROM   DATEINFO
         WHERE  DATES < @TODATE)
SELECT *
FROM   DATEINFO
OPTION (MAXRECURSION 0) 

OPEN @weekdates

FETCH next FROM @weekdates INTO @adate

WHILE @@fetch_status = 0
  BEGIN
      PRINT 'success'

      FETCH next FROM @weekdates INTO @adate
  END

当声明为局部@变量时,游标会在变量超出范围时自动关闭并释放。

于 2013-01-30T16:05:46.857 回答