从另一个多记录表更新多个记录表

时间:2018-06-14 05:02:03

标签: sql sql-server stored-procedures

我不知道关于它的正确标题。 但是,让我解释一下我的问题。

我有2张桌子

PartTable
-------------------------------
ID  |  Quantity
1   |  10
2   |  10
3   |  10

TransTable
-------------------------------
TransID |ID  |  QtyIssue
1       |1   |  2
1       |2   |  2
1       |3   |  2

对于TransTable,我使用单个查询来插入。

如何在单个查询中更新PartTable上的数量?

Quantity = Quantity - QtyIssue

我正在使用此更新声明:

UPDATE PartTable SET Quantity = Quantity - (SELECT QtyIssue FROM TransTable WHERE TransID = 1)
WHERE ID IN (SELECT ID FROM TransTable WHERE TransID = 1)

但错误:

Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.

有可能吗?

请帮助任何人。感谢。

2 个答案:

答案 0 :(得分:2)

您可以使用派生表更新它

UPDATE  PartTable
        SET Quantity = Quantity - b.QtyIssue
FROM    PartTable a 
INNER JOIN (
SELECT  SUM(QtyIssue) QtyIssue,ID
FROM    TransTable  WHERE TransID = 1
GROUP BY ID) b ON   a.ID  = b.ID 

答案 1 :(得分:0)

在这里你去&gt;&gt;

a list of items