I’m stuck in this problem for quite while now. I have two tables ItemMaster and ItemStock and in ItemStock table I have a column ItemId, which is foreign key to Id column of ItemMaster table, and whenever I add new quantity in ItemStock table, I want that quantity value automatically gets summed with already exited quantity in the ItemMaster based on ItemId of ItemStock table.
ItemMaster:
Id ItemName Quantity
---------- ----------- -----------
1 Item1 50
2 Item2 50
ItemStock:
Id ItemId Quantity
---------- ----------- -----------
1 1 20
2 2 30
Query in SQL Server 2005:
with Developer([sum], itemid, stockid)
as
(
select
sum(stock.quantity + isNull(im.quantity, 0)) as [sum],
im.id as Itemid, stock.itemid as stockid
from ItemMaster im
inner join ItemStock stock on stock.itemid = im.id
group by im.id, stock.itemid
)
update ItemMaster
set quantity = (Select [sum] from Developer)
Results in an error:
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.
Could anyone please tell me how can I solve this problem?
Aren’t you missing a
WHEREclause in your UPDATE statement??Right now, if you do a
SELECT * FROM Developer, you get:and that’s exactly what the error says – the query returns more than a single results, so what is the UPDATE supposed to do with this?? It cannot set the
quantitycolumn to more than a single value…..Just guessing – do you maybe mean to do this?
Add the
WHEREclause to associate one row fromDeveloperwith a single row inItemMaster