Perform UPDATE with values from another table, in columns with the same name

Asked

Viewed 1,432 times

2

I have the following tables table and table, These tables have about 20 identical columns. What I need to do is update the values of the tabela_B to start from the tabela_A, where the columns are the same.

There is a way to automate the UPDATE process without having to reference the columns one by one through a JOIN?

3 answers

4

  • Thank you, Thomas. But this way I need to quote all 20 (or more) columns to be updated, and I’m trying to find a way not to need this.

  • "..without having to reference the columns one by one through a JOIN?" - The question prompts to update without citing the columns.

1


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;
  • Making some changes but the hint of using CURSOR has done a lot of good.

0

You cannot update multiple tables in the same query, however, you can use a transaction to make sure that the two querys of UPDATE are treated:

BEGIN TRANSACTION;

UPDATE Table1
  SET Table1.LastName = 'DR. XXXXXX' 
FROM Table1 T1, Table2 T2
WHERE T1.id = T2.id
and T1.id = '011008';

UPDATE Table2
SET Table2.WAprrs = 'start,stop'
FROM Table1 T1, Table2 T2
WHERE T1.id = T2.id
and T1.id = '011008';

COMMIT;
  • Thank you, Bruno. But I want to update only the tabela_B, with values from the tabela_A.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.