How to INSERT INTO #TEMPTABLE without deleting the data of the table

时间:2019-04-16 22:42:58

标签: sql sql-server

I am creating code that creates a table called #Transferencia, it has 31 columns.

I made an insert into it to populate 16 of its columns. When I do another insert into to populate more columns, it makes all other values as NULL

Example of my first INSERT INTO

INSERT INTO #Transferencia (ID_Cota, CHAVE, CD_Grupo)
SELECT 
      a.id_cota,
      CONCAT(convert(numeric(10,0),(b.CD_Grupo)),'-',a.CD_Cota),
      b.CD_Grupo

Example of my second INSERT INTO that deletes my previous one


INSERT INTO  #Transferencia (Usuario, NM_Pessoa_Vendedor)
SELECT 
      c.cd_usuario, 
      d.NM_Pessoa

When I finish my second INSERT, the columns (ID_Cota, CHAVE, CD_Grupo) become null

Is there any alternative that I can 'populate' those others colunms by a select?

PS: The code is way more complex, I've simplified it for the sake of this question

1 个答案:

答案 0 :(得分:0)

It sounds like you want an update for the second operation:

INSERT INTO #Transferencia (ID_Cota, CHAVE, CD_Grupo)
    SELECT a.id_cota,
          CONCAT(convert(numeric(10,0),(b.CD_Grupo)),'-',a.CD_Cota),
          b.CD_Grupo;

Example of my second INSERT INTO that deletes my previous one

UPDATE t
    SET Usuario = c.cd_usuario, 
         NM_Pessoa_Vendedor = d.NM_Pessoa
FROM #Transferencia t . . .
     c . . .
     d . . .

The FROM clause is your query with JOINs and so on.