Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Skip a row(an iteration) in MSSQL Cursor based on some condition?

How Can I Skip a row(an iteration) in MSSQL Cursor based on some condition, I have a DTS which migrates thousands of records and based on some criteria, some records need not be migrated as they are duplicates and want to skip these records.

Any idea how I can accomplish this in MSSQL Cursor?

like image 727
David LA Avatar asked Jan 11 '23 01:01

David LA


1 Answers

I guess the simplest way is to write IF statement inside the cursor. If the condition will be false you will skip records.

 DECLARE @ID INT
 DECLARE Curs CURSOR FAST_FORWARD
 DECLARE @Cnt INT

 CREATE TABLE ##Duplicates (ID INT, CarColor VARCHAR (50) )

 FOR
        SELECT DISTINCT  CarID
        FROM    dbo.CarPark
        WHERE   CarColour <> 'red'
        ORDER BY CarID

    OPEN Curs

        FETCH NEXT FROM Curs INTO @ID

        WHILE @@FETCH_STATUS = 0

    BEGIN

             INSERT INTO  ##Duplicates
             SELECT CarID, CarColor
             FROM  dbo.CarPark          
             WHERE ID = @ID;

             SET @Cnt = (SELECT Count(*) FROM ##Duplicates WHERE ID = @ID) ;

             IF @Cnt < 2 
             THEN /* Migrate */
             ELSE PRINT 'Duplicate'
             END

        FETCH NEXT FROM Curs INTO @ID 

        END

    CLOSE Curs
    DEALLOCATE Curs;
like image 93
Almazini Avatar answered Jan 16 '23 17:01

Almazini