Sunday, September 29, 2013

 Basic Intro to Cursor in MS SQL


Cursor works as a foreach loop in ms sql.  
@@FETCH_STATUS = 0 -> The FETCH statement was successful if  ,
@@FETCH_STATUS = -1 -> The FETCH statement failed or the row was beyond the result set,
@@FETCH_STATUS = -2 -> The row fetched is missing.


DECLARE @ServiceId INT
    DECLARE @ContentId INT
    DECLARE @ContentExist INT = 1

    --cursor start
    DECLARE monitoring_cursor CURSOR
    FOR
    SELECT ID
        ,ContentID
    FROM dbo.[Services]
   
    OPEN monitoring_cursor

    FETCH NEXT
    FROM monitoring_cursor
    INTO @ServiceId
        ,@ContentId



    WHILE @@FETCH_STATUS = 0
    BEGIN
        IF NOT EXISTS (
                SELECT *
                FROM dbo.ContentData
                WHERE ContentID = @ContentId
                  )
        BEGIN
            SET @ContentExist = 0;
        END

        IF @ContentExist = 0
        BEGIN
            INSERT INTO dbo.Monitoring (
                [Date]
                ,[Status]
                ,[Description]
                )
            VALUES (
                GETDATE()
                ,'Failed'
                ,'Service' + @ServiceId + 'no content'
                )
        END
        ELSE
        BEGIN
            INSERT INTO dbo.Monitoring (
                [Date]
                ,[Status]
                ,[Description]
                )
            VALUES (
                GETDATE()
                ,'OK'
                ,NULL
                )
        END

        FETCH NEXT
        FROM monitoring_cursor
        INTO @ServiceId
            ,@ContentId
    END

    CLOSE monitoring_cursor

    DEALLOCATE monitoring_cursor
        --- cursor end

No comments:

Post a Comment