You can make a script to generate the update and then run it dynamically.
Creating the structure of the base:
CREATE TABLE Table1
([Id] int, [name] varchar(50));
CREATE TABLE Table2
([Id] int, [name] varchar(50));
INSERT INTO Table1
([Id], [Name])
VALUES
(1, 'C3PO'),
(2, 'R2D2'),
(3, 'BB8');
INSERT INTO Table2
([Id], [Name])
VALUES
(1, 'Luke'),
(2, 'Darth');
Creating the script that will generate UPDATE run it:
declare @query NVARCHAR(MAX)
declare @name VARCHAR(50)
set @query = 'update table2 set '
DECLARE cursor1 CURSOR FOR
select name from syscolumns
where [id] = (select [id] from sysobjects where name = 'Table1') -- Busca o objeto da tabela referência
OPEN cursor1
FETCH NEXT FROM cursor1 INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
set @query = @query + 'Table2.' + @name + ' = Table1.' +@name + ','
FETCH NEXT FROM cursor1 INTO @name
END
set @query = substring(@query, 1, (len(@query) - 1)) + ' from Table1 INNER JOIN Table2 ON Table1.id = Table2.id'
print @query; -- Verifica a query gerada
execute sp_executesql @query; -- Executa a query
CLOSE cursor1;
DEALLOCATE cursor1;
Columns are identical and in the same order?
– Andrew Paes
Yeah, @Andrewpaes
– Marcelo de Andrade