現在我陷入了這個問題。我有兩個表ItemMaster
和ItemStock
和ItemStock
表我有一列ItemId
,這是外鍵ItemMaster
表的Id
列,每當我在ItemStock
表中添加新的數量,我想那量值自動獲取與已經退出數量相加在ItemMaster
的基礎上ItemId
的ItemStock
表。在添加兩個表的列時出錯:SQL Server 2005
ItemMaster:
Id ItemName Quantity
---------- ----------- -----------
1 Item1 50
2 Item2 50
ItemStock:
Id ItemId Quantity
---------- ----------- -----------
1 1 20
2 2 30
查詢在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)
導致錯誤:
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.
任何人都可以請告訴我如何解決這個問題?
是否有一個原因,爲什麼你要存儲這個值(它可能很容易過時,如果有某種方式繞過你的更新代碼)而不是使用總是會有正確值的視圖(可能是索引視圖)? –
爲什麼你不使用觸發器嗎?,這可能會更容易。 – Kangkan
感謝您的建議 – Dusk