2
I have a temporary table that I fill with the result of a particular query.
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.
I can’t just use INSERT INTO ... SELECT (as I use in my script at other points)
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
Have you tried using
Cursor
? With it you can consult and manipulate the information onselect
from temporary table and do treatments line by line.– Willian
@Willian didn’t try to use it. I need to learn about it in order to use it, because I’m a beginner in SQL. I would have some article to share, please?
– Felipe Negro
You can look at these here: http://www.devmedia.com.br/cursores-no-sqlserver/5590. I will put together an answer to try to simplify because it is a more advanced concept and I myself have had a certain difficulty in understanding
– Willian
Possible duplicate of Capture values from one table and insert them into another
– José Diz
@Josédiz did, in fact. I could not delete the topic you mentioned, unfortunately the title did not match what I needed, I tried to edit it, but it was not possible.
– Felipe Negro
@Felipenegro Managed to solve the problem using Cursor?
– Willian
@Felipenegro: How is the coupon code generated? What are the rules for entering the data in the "other table"? What is the name and structure of the "other table"?
– José Diz