Reputation: 79
I don't know the right title about it. But, Let me explain about my question.
I have 2 tables
PartTable
-------------------------------
ID | Quantity
1 | 10
2 | 10
3 | 10
TransTable
-------------------------------
TransID |ID | QtyIssue
1 |1 | 2
1 |2 | 2
1 |3 | 2
for TransTable, I'm using single query to insert.
How to update Quantity on PartTable in single Query?
Quantity = Quantity - QtyIssue
I'm using this update statement:
UPDATE PartTable SET Quantity = Quantity - (SELECT QtyIssue FROM TransTable WHERE TransID = 1)
WHERE ID IN (SELECT ID FROM TransTable WHERE TransID = 1)
But error :
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.
Is it possible?
Please help anyone. Thanks.
Upvotes: 0
Views: 52
Reputation: 4882
Here you go >>
UPDATE parttable pt
SET pt.quantity = pt.quantity - (SELECT tt.qtyissue
FROM transtable tt
WHERE tt.transid = 1
AND tt.id = pt.id)
WHERE pt.id IN (SELECT tt1.id
FROM transtable tt1
WHERE tt1.transid = 1)
Upvotes: 0
Reputation: 1728
You Can Update It by Using Derived Table
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
Upvotes: 2