Я борюсь с переносом данных в SQL в новый столбец (что не сложно, потому что я совершенно неопытен в SQL XD). Я попытаюсь описать проблему:
I need to transfer some data using UPDATE statement from existing <i>tableB.potatoes</i> to
new created column <i>potatoes_new</i> in existing <i>tableA</i> (<i>tableB.potatoes</i> -> <i>tableA.potatoes_new</i>
Conditions:
-tableB has foreign key tableB.tableA_ID referencing tableA.ID
-tableB.potatoes and tableB.tableA_ID are not unique but in registers with same tableA_ID, potatos is also the same:
example:
tableB tableA
ID tableA_ID potatoes ID potatoes_new(current) potatoes_new(desired)
1 1 105 1 NULL 105
2 1 105 2 NULL 51
3 2 51 3 NULL 33
4 3 33
5 3 33
6 3 33
It is not necessary to delete the data from tableB.columnA, just copy to the <b>RIGHT</b> register:
-> where tableA.ID = tableB.tableA_ID
Я искал некоторое время, но не нашел то, что хочу (или, по крайней мере, я не понял, как эти решения могут решить мою проблему ...)
PS: Это мой первый пост ... извините за формат, я пытался какое-то время немного не справиться лучше. Если у вас есть какие-то подсказки или ссылки ... Я был бы признателен за это
РЕДАКТИРОВАТЬ: Решение (после того, как GabrielVal помог мне с его ответом)
Changes I had to do to GabrielVal answer:
1. I had to substitute the tableB to a as the MERGE statement was having problems finding several records in tableB in which tableB.tableA_ID = tableA.ID
2. Thus I deleted the INSERT INTO WHEN NOT MATCHED because I did not want to create new records on tableA, but just fill the current ones
MERGE dbo.tableA as [target]
USING (SELECT DISTINCT tableA_ID,potatoes_new FROM tableB WHERE Measurement_ID != 0 ) as [source]
ON [source].tableA_ID = [target].ID
WHEN MATCHED THEN
UPDATE SET [target].SystemID = [source].System_ID;
GO