While always returns the last record in sql server

Asked

Viewed 127 times

0

I have a select to bring all the records that have been entered and I need to do a while to go through this select and give an Insert in another temporary table. Only that the 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

inserir a descrição da imagem aqui

  • What’s in @P_PLANO_CTA_COD_RED ?

  • it takes the value declared in a variable there was 18906 as you can see in the image

  • inside your while you recover all the records of #tableConta since your PLANOCODRED is the same for all lines. Is this what you want to do ? What’s more, the Insert into with select does not serve you in this case ?

  • what would that be like? There are some examples?

  • See if it answers. Example

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;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.