Search code examples
sql-servercursorclustered-index

Clustered Index Update from within a cursor issue


I have a clustered index that is over several fields. One of these fields is CustomerID. I have a cursor that reads from that table, and then updates the CustomerID. The problem is that it cause an infinite loop. I assume that when it changes the customerid field, the clustered index is modified and the table is restructured for the index. This modification seems to invalidate my cursor so the FETCH NEXT FROM Cursor never reaches the end.

    FETCH NEXT FROM AccountSoftwareRegCursor 
INTO @CurrentAccountSoftwareRegUId

    WHILE (@@FETCH_STATUS = 0)
    BEGIN

    UPDATE 
        Licensing.AccountSoftwareRegistration 
    SET 
        AccountUid = @ToAccountUid, 
        CompanyId = @ToCompanyId, 
        UpdatedBy = isnull(@UpdatedBy,'Asset Transfer'),
        UpdatedByAccount = @UpdatedByAccount,
        UpdatedOn = GETUTCDATE()
    WHERE 
        AccountSoftwareRegUid = @CurrentAccountSoftwareRegUId

Is there any command i can issue to stop the table from updating the table for the clustered index until after the cursor finishes?


Solution

  • If you cannot rewrite this to eliminate the cursor, you'll want to declare your cursor as STATIC.

    DECLARE AccountSoftwareRegCursor CURSOR STATIC
    FOR
    SELECT...
    

    From the DECLARE CURSOR documentation:

    STATIC

    Defines a cursor that makes a temporary copy of the data to be used by the cursor. All requests to the cursor are answered from this temporary table in tempdb; therefore, modifications made to base tables are not reflected in the data returned by fetches made to this cursor, and this cursor does not allow modifications.