While always returns the last record in sql server

0

I have a select to bring all the records that have been entered and I need to do a while to cycle through this select and give an insert in another temporary table. Only while is always bringing the last record

What could be wrong?

        DECLARE @CONTADOR INT 
        DECLARE @CONTADORLOOP INT = 1

        SELECT @CONTADOR = COUNT(*) FROM #tableConta

        SELECT * FROM #tableConta

        WHILE(@CONTADORLOOP IS NOT NULL AND @CONTADORLOOP <= @CONTADOR)
        BEGIN

            SELECT @EMP_VLR = EMPCOD, @PLANO_COD_RED = PLANOCODRED FROM #tableConta where PLANOCODRED = @P_PLANO_CTA_COD_RED

            PRINT @EMP_VLR
            --INSERT INTO #tableDebCred (TOTAL2, EMPCOD2, PLANOCODRED) VALUES (@VLRTOTAL2, @EMP_VLR, @PLANO_COD_RED)

                SET @CONTADORLOOP = @CONTADORLOOP  + 1 

        END

    END

    
asked by anonymous 28.11.2018 / 13:14

1 answer

1

If I understand correctly I believe that a Insert with Select would meet your need

INSERT INTO TABLEDEBCRED (TOTAL2, EMPCOD2, PLANOCODRED)
SELECT @TOTAL2, EMPCOD, PLANOCODRED FROM TABLECONTA
    WHERE PLANOCODRED = @P_PLANO_CTA_COD_RED;
    
28.11.2018 / 14:10