在LOOP错误时设置DATEFIRST CURSOR - 设置选项已更改

时间:2018-06-12 08:35:00

标签: sql-server date while-loop cursor

我的光标循环非常奇怪,这就是我得到的;

DECLARE @StartDate AS DATE
DECLARE @ID INT
DECLARE CursorTest CURSOR FOR  
SELECT ID FROM tblSomething

OPEN Schedule
FETCH NEXT FROM CursorTest INTO @ID

WHILE @@FETCH_STATUS = 0
    BEGIN
        SELECT @StartDate = StartDate FROM tblAnother WHERE ID = @ID
        SELECT @StartDate --12/06/2018
        -- NOW WE MOD IT
        SET DATEFIRST 6 -- WE START ON SATURDAY 1
        SET @StartDate = DATEPART(dw,@StartDate)
        SELECT @StartDate -- ANSWER IS 4
        FETCH NEXT FROM CursorTest INTO @ID
    END

CLOSE CursorTest
DEALLOCATE CursorTest

现在,如果我运行这个,我会到达CURSOR的第二行,它会崩溃和状态;

Could not complete cursor operation because the set options have changed since the cursor was declared.

现在,如果我注释掉了;

--SET DATEFIRST 6

错误消失了,所以我认为SET DATEFIRST正在修改导致错误的数据库。

周围有没有像这样的东西;

SET @StartDate = DATEPART(dw,@StartDate,DATEFIRST 6)

这些方面的东西。

2 个答案:

答案 0 :(得分:1)

您可以移动DECLARE @StartDate AS DATE DECLARE @ID INT DECLARE CursorTest CURSOR FOR SELECT ID FROM tblSomething SET DATEFIRST 6 -- WE START ON SATURDAY 1 OPEN Schedule FETCH NEXT FROM CursorTest INTO @ID WHILE @@FETCH_STATUS = 0 BEGIN SELECT @StartDate = StartDate FROM tblAnother WHERE ID = @ID SELECT @StartDate --12/06/2018 -- NOW WE MOD IT SET @StartDate = DATEPART(dw,@StartDate) SELECT @StartDate -- ANSWER IS 4 FETCH NEXT FROM CursorTest INTO @ID END CLOSE CursorTest DEALLOCATE CursorTest

charset.NewReader

答案 1 :(得分:0)

我修好了;

SET DATEFIRST 6 -- outside CURSOR LOOP;
WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @StartWeek = DATEPART(wk,@StartDate) -- CORRECT BY DATEFIRST 6
        SET @StartDay = (DATEPART(dw,@StartDate) + @@DATEFIRST - 1 - 1) % 7 + 1 -- MONDAY 1
    END