[英]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. 有200列,因此无法为所有列set tabA.colA = tabB.colA
。 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 您可以在@UpdateStatement中添加任何要添加的条件
Simply write out the UPDATE
statement and SET all the columns you need to change. 只需写出UPDATE
语句并设置所有需要更改的列即可。
It's a bit of initial work. 这是一些初期工作。
But as long you're not regulary adding/removing columns, the SQL can be re-used. 但是只要您不定期添加/删除列,就可以重新使用SQL。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.