简体   繁体   中英

SQL server updating a table

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM