How to update or insert data from one table to another table in the same database in SQL

1

Good morning one more time I need to get used to greeting help

The problem I have is that I want to update a table with the data of another table always in the same database in SQL but for reasons of life has not updated me this is the script I always use:

UPDATE TablaDestino SET TablaDestino.ID = (Select CompoActulizar FROM TablaOrigen AS m) 

but it does not update me I wanted to know if they could help me and how would it be when I want to update more than one field

thanks. Blessings

    
asked by Jose 24.04.2018 в 17:05
source

2 answers

2

When you need to execute a scrit in a single database, use:

USE[BaseDatos]

And below it, all the script to execute on that base.

Another option is to indicate completely the name of the table, database + scheme + name, that is:

TuBase.TuEsquema.TuTabla

DBPrueba.dbo.Tabla

It should be noted that "dbo" is the standard scheme, if you did not specify it when you created the table.

In your situation I would think that the error is not in what base you are using but rather in your script.

Your sub-select can return many values, so you must use a Top (1), so that it only returns one result, in the following way:

UPDATE TablaDestino 
SET TablaDestino.ID = (SELECT TOP(1) CompoActulizar FROM TablaOrigen AS m)

I hope the explanation has helped you solve your problem, regards.

    
answered by 24.04.2018 в 17:18
0

Update several fields:

UPDATE TablaDestino 
SET TablaDestino.Campo1 = (SELECT CompoActulizar1 FROM TablaOrigen),  
TablaDestino.Campo2 = (SELECT CompoActulizar2 FROM TablaOrigen)

Why do not you update?

Has answered the partner Rostan

EDITING AFTER THIS COMMENT

  

The destination table is empty and I want to update the ID, that is to say that all the id of the origin I put them in the tableDestino - Jose 10 minutes ago

INSERT INTO tabla2(columna1, columna2, columna3, ...)
SELECT columna1, columna2, columna3, ...
FROM tabla1
WHERE concicion;

Since you have not passed a structure of your tables, I hope this example serves you

    
answered by 24.04.2018 в 17:22