• An example of a cursor you can find in this post http://www.sqlservercentral.com/articles/cursors/65136/, but don't forget to read the discution for there is some discution possible wether it is a good thing to use cursor.

    For the error-handling

    -- Error-declarations --

    DECLARE@MyErrNumber int,

    @MyErrSeverity int,

    @MyErrState int,

    @MyErrLine int,

    @MyErrProcedure nvarchar(128),

    @MyErrMessage nvarchar(4000);

    SET @MyErrNumber = 0

    --

    BEGIN TRY

    -- execution (begin)

    -- execution (end)

    END TRY

    BEGIN CATCH

    SELECT @MyErrNumber = ERROR_NUMBER(),

    @MyErrSeverity = ERROR_SEVERITY(),

    @MyErrState = ERROR_STATE(),

    @MyErrLine = ERROR_LINE (),

    @MyErrProcedure = ERROR_PROCEDURE(),

    @MyErrMessage = ERROR_MESSAGE()

    select @MyErrNumber As ErrNumber

    ,@MyErrSeverity As ErrSeverity

    ,@MyErrState As ErrState

    ,@MyErrLine As ErrLine

    ,@MyErrProcedure As ErrProcedure

    ,@MyErrMessage As ErrMessage ;

    -- close open transactions (only valid for transactions in try-block)

    IF @@TRANCOUNT > 1

    BEGIN

    ROLLBACK TRAN

    END

    -- DO something with error-values here

    END CATCH;