I'm trying to update a table from another one. There are 200 columns so can't do set tabA.colA = tabB.colA
for all the columns. Is there another solution for that?
-
2Simply hard work typing a lot.– jarlhCommented Jan 30, 2019 at 9:28
-
2Just use excel to generate all mappings :)– Alexander VolokCommented Jan 30, 2019 at 9:31
-
2There are 200 columns so can't do... well you can, you just don't want to– ta.speot.isCommented Jan 30, 2019 at 10:11
-
@AlexanderVolok what i did thanks!– Badr ErrajiCommented Jan 30, 2019 at 13:17
-
@ta.speot.is yes i have to do it for many files aggregating to 1000+ columns so no i can't do it without spending the day on it :) so i followed alexander volok: Created a spreadsheet in excel, a cell for tabA name a cell for tabB name and a column with all the column names and i did a simple formula in excel that did it in 3 seconds instead of 2 hours and adaptable to any table . plus PSK gave a dynamic query i didn't test it but that's a pretty smart way to handle this issue in the long run :)– Badr ErrajiCommented Jan 30, 2019 at 13:17
Add a comment
|
2 Answers
There is no shortcut for this except building a dynamic query.
If the column name are same in both the tables you can try like following.
DECLARE @UpdateStatement VARCHAR(max)
SET @UpdateStatement = 'UPDATE Destination SET ' + CHAR(10)
SELECT @UpdateStatement = @UpdateStatement + 'Destination.' + COLUMN_NAME + ' = Source.' + COLUMN_NAME + ', ' + CHAR(10)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Destination'
-- append the TABLE NAME and WHERE condition to @UpdateStatement
PRINT @UpdateStatement
You can add whatever condition you want to add in your @UpdateStatement
Simply write out the UPDATE
statement and SET all the columns you need to change.
It's a bit of initial work.
But as long you're not regulary adding/removing columns, the SQL can be re-used.
UPDATE t
SET
colA = b.colA
, colB = b.bolB
-- add more columns here
FROM tableA t
JOIN tableB t2 ON -- <<the fields that the tables can be joined on>>
Example snippet:
-- using table variables for demonstration purposes
declare @tableA table (id int primary key identity(1,1), colA varchar(30), colB varchar(30), colC varchar(30));
declare @tableB table (id int primary key identity(1,1), tableAId int, colA varchar(30), colB varchar(30), colC varchar(30));
insert into @tableA (colA, colB, colC) values ('A1','A2','A3'),('A4','A5','A6');
insert into @tableB (tableAId, colA, colB, colC) values (1, 'B1','B2','B3'),(2, 'B4','B5','B6');
update t
set
colA = t2.colA,
colB = t2.colB,
colC = t2.colC
from @tableA t
join @tableB t2 on t2.tableAId = t.id;
select *
from @tableA;