Capture values from one table and insert them into another table

1

I have a temporary table that I fill in with the result of a given query. Now I need to go through the data of this temporary table, line by line, and pick certain fields and insert them into another table, and in that other table, generate a coupon code, with a specific sequence, to complete the process.

How can I make this loop catch line-by-line from temporary table?

    CREATE TABLE #PontosVPAcimaCem (
        qtd_cupons INT
        ,apuracao_ptsvp NUMERIC(14, 2)
        ,apuracao_mesfch INT
        ,apuracao_anofch INT
        ,apuracao_id_client INT
        ,clients_username NVARCHAR(150)
        )

    INSERT INTO #PontosVPAcimaCem (
        qtd_cupons
        ,apuracao_ptsvp
        ,apuracao_mesfch
        ,apuracao_anofch
        ,apuracao_id_client
        ,clients_username
        )
    SELECT CAST(a.ptsvp / 100 AS INT)
        ,a.ptsvp
        ,a.mesfch
        ,a.anofch
        ,a.id_client
        ,c.username
    FROM t_clients c WITH (NOLOCK)
    INNER JOIN gr_apuracao a WITH (NOLOCK) ON c.id = a.id_client
    WHERE a.mesfch = @apuracao_mes
        AND a.anofch = @apuracao_ano
        AND a.ptsvp >= @apuracao_pontosvp

    SELECT qtd_cupons
        ,apuracao_ptsvp
        ,apuracao_mesfch
        ,apuracao_anofch
        ,apuracao_id_client
        ,clients_username
    FROM #PontosVPAcimaCem WITH (NOLOCK)
    ORDER BY qtd_cupons DESC
    
asked by anonymous 19.12.2016 / 19:15

2 answers

1

I was able to solve my problem using cursor. In this thread there is the answer.

Going line by line from a table

    
22.12.2016 / 11:42
1

You can use SQL INSERT INTO SELECT

The function is to copy data from a table to an existing table.

Example without the declaration of the columns to insert, which can be used in cases where you are copying the data between two tables with the same structure

INSERT INTO table2
SELECT * FROM table1;

Another possibility is for you to declare the columns.

INSERT INTO table2
(column_name(s))
SELECT column_name(s)
FROM table1;
    
19.12.2016 / 20:03