Capture values from one table and insert them into another

Asked

Viewed 509 times

1

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

How can I make this loop to capture row by row from the 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

2 answers

1

You can use the SQL INSERT INTO SELECT

The function of which is to copy the data from one existing table to another.

Example without the declaration of the columns to be inserted, 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;

1


Browser other questions tagged

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