Using a cursor with a CTE

后端 未结 2 1876
借酒劲吻你
借酒劲吻你 2021-01-03 22:35

I need a cursor for the below query so I can loop through to fetch/update/insert some other data. Can somebody help me with this?

DECLARE @FROMDATE DATETI         


        
2条回答
  •  醉话见心
    2021-01-03 23:22

    It is fine to use @ in a cursor name but the syntax you are using is wrong.

    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
    

    When declared as a local @ variable the cursor is automatically closed and deallocated when the variable goes out of scope.

提交回复
热议问题