これを行うこともできます (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
すべての行に一致する an に変更するには、単にhttp://www.sqlfiddle.com/#!3/8b5a3/27INNER JOIN
に変更しLEFT JOIN
ます
update p SET
Qty = ISNULL(t.Qty,0)
from Product p
left join Latest t
on t.ProductId = p.ProductId;
select * from Product;
一方、一致した行のみでANSI SQLUPDATE
を作成したい場合... 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);