您也可以这样做(适用于 SQL Server 和所有符合 ANSI SQL 的数据库):
UPDATE [Product] SET
[Product].[Active] = 1
,[Product].[Color] = t.[Color]
FROM @Table t
WHERE t.[ProductID] = [Product].[ProductID]
SQL Server 的专有 UPDATE FROM 有一些需要改进的地方,您可以轻松地更改UPDATE
语句以使其匹配整个表,无论是否没有匹配的行。
很容易塑造这个仅匹配行的更新...... http://www.sqlfiddle.com/#!3/8b5a3/26
update p SET
Qty = t.Qty
from Product p
inner join Latest t
on t.ProductId = p.ProductId;
...要UPDATE
匹配所有行,您只需将其更改INNER JOIN
为LEFT JOIN
:http ://www.sqlfiddle.com/#!3/8b5a3/27
update p SET
Qty = ISNULL(t.Qty,0)
from Product p
left join Latest t
on t.ProductId = p.ProductId;
select * from Product;
而如果你想UPDATE
用匹配的行来塑造 ANSI SQL ... http://www.sqlfiddle.com/#!3/8b5a3/28
update Product SET
Qty = t.Qty
from Latest t
where t.ProductId = Product.ProductId
...要UPDATE
匹配所有行的语句,您必须稍微调整查询:http ://www.sqlfiddle.com/#!3/8b5a3/29
update Product SET
Qty = ISNULL(t.Qty, 0)
from
(
select x.ProductId, lat.Qty
from Product x
left join Latest lat on lat.ProductId = x.ProductId
) as t
where t.ProductId = Product.ProductId;
尽管作为开发中的大多数选择,人们应该权衡代码可读性/可维护性与灵活性方面的利弊
数据样本:
create table Product
(
ProductId int primary key not null,
Name varchar(50) not null,
Qty int not null
);
insert into Product(Name,Qty) values
(1,'CAR',1),
(2,'Computer',1000),
(3,'Shoes',2);
create table Latest
(
ProductId int primary key not null,
Qty int not null
);
insert into Latest(ProductId, Qty) values
(2,2000),
(3,3);