为什么我会得到“名称已存在的游标”?

时间:2015-02-28 19:47:49

标签: sql sql-server tsql cursor

我有这个触发器:

CREATE TRIGGER CHECKINGMAXQTYDAYSVACANCY
    ON TDINCI
AFTER INSERT 
AS
    DECLARE
        @incidentCode int,
        @dateStart datetime,
        @dateEnd datetime,
        @daysAccumulated int,
        @maxDaysAvailable int

    set @daysAccumulated = 0;

    select @incidentCode = CO_INCI from inserted;
    select @maxDaysAvailable = IN_DIAS_GANA from TCINCI
        where CO_INCI = @incidentCode;

    declare detailsCursor CURSOR FOR
        select FE_INIC, FE_FINA from TDINCI
        where CO_INCI = @incidentCode;

    open detailsCursor;

    if CURSOR_STATUS('variable', 'detailsCursor') >= 0
    begin
        fetch next from detailsCursor
            into @dateStart, @dateEnd;

        while @@FETCH_STATUS = 0
        begin
            set @daysAccumulated = @daysAccumulated + (DATEDIFF(DAY, @dateStart, @dateEnd) + 1);

            fetch next from detailsCursor
            into @dateStart, @dateEnd;
        end
        close detailsCursor;
        deallocate detailsCursor;
    end
    IF(@maxDaysAvailable > @daysAccumulated)
    BEGIN
        RAISERROR ('No se pueden ingresar mas dias de los programados en la cabecera de incidencias.', 16, 1);
        ROLLBACK TRANSACTION;
        RETURN 
    END
GO

当我对表TDINCI进行插入

INSERT INTO TDINCI 
VALUES (1, '20150101', '20150115', '2015-2015')

我收到错误:

  

名称为' detailsCursor'的光标已经存在。

我打开

open detailsCursor;

并关闭光标。

close detailsCursor;
deallocate detailsCursor;

也许我无法管理光标范围?提前谢谢。

1 个答案:

答案 0 :(得分:71)

您正在使用全局游标,每次调用此过程时都会定义该游标并给出相同的错误。

定义本地光标。只需将关键字LOCAL放在CURSOR之后:

declare detailsCursor CURSOR LOCAL FOR
...