使用带有CTE的光标

时间:2013-01-30 10:12:21

标签: sql sql-server common-table-expression

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

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

我仍然遇到错误

2 个答案:

答案 0 :(得分:26)

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

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) 

(但是,插入关于游标的常见注意事项几乎总是错误的工具。如果你能找到一种方法以基于集合的方式完成整个操作,它通常更可取,并且可能表现更好(或者在至少更适合性能调整))

答案 1 :(得分:12)

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

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

当声明为本地@变量时,当变量超出范围时,光标会自动关闭并释放。