Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
添加两个表的列时出错:SQL Server 2005_Sql_Sql Server 2005_Tsql - Fatal编程技术网

添加两个表的列时出错:SQL Server 2005

添加两个表的列时出错:SQL Server 2005,sql,sql-server-2005,tsql,Sql,Sql Server 2005,Tsql,我陷入这个问题已有一段时间了。我有两个表ItemMaster和ItemStock,在ItemStock表中我有一个列ItemStock,它是ItemMaster表的Id列的外键,每当我在ItemStock表中添加新数量时,我希望根据ItemStock表的ItemId自动将该数量值与ItemMaster中已存在的数量相加 ItemMaster: Id ItemName Quantity ---------- ----------- ---------

我陷入这个问题已有一段时间了。我有两个表
ItemMaster
ItemStock
,在
ItemStock
表中我有一个列
ItemStock
,它是
ItemMaster
表的
Id
列的外键,每当我在
ItemStock
表中添加新数量时,我希望根据
ItemStock
表的
ItemId
自动将该数量值与
ItemMaster
中已存在的数量相加

ItemMaster:

   Id         ItemName     Quantity        
---------- -----------  ----------- 
    1           Item1       50
    2           Item2       50
项目库存:

    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) 
导致错误:

子查询返回了多个值。在以下情况下,这是不允许的: 子查询如下=,!=,=或者当使用子查询时 作为一种表达方式。
声明已终止


有谁能告诉我如何解决这个问题吗?

您的更新语句中是否缺少
WHERE
子句

现在,如果您执行一个
SELECT*FROM Developer
,您将得到:

sum itemid  stockid
 70   1        1
 80   2        2
这正是错误所说的-查询返回的结果不止一个,那么更新应该如何处理它呢??它不能将
数量
列设置为多个值

只是猜测-你是不是真的想这么做

;WITH Developer.......
(
     ......
)
UPDATE dbo.ItemMaster
SET quantity = dev.sum
FROM Developer dev
WHERE dbo.ItemMaster.ItemId = dev.ItemId   

添加
WHERE
子句,将
Developer
中的一行与
ItemMaster

中的一行相关联。您的选择返回多个记录,因为您使用的是简单联接,所以您应该插入一个WHERE子句以按id进行筛选。类似于这样的情况

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
where im.id = @MyId and stock.itemid = @MyID2

我还将删除select中的其他字段,因为您不需要它们。只保留总和(选择更清晰的imo)

您可以创建一个视图:

CREATE VIEW ItemsOnHand
WITH SCHEMABINDING
AS
    SELECT ItemID,SUM(Quantity) as Quantity,COUNT_BIG(*) as Cnt
    FROM dbo.ItemStock

这种观点总是正确的。如果性能是一个问题,您还可以将此视图编入索引(在
ItemID上)
,这意味着SQL Server将把它作为一个隐藏表进行维护,在
ItemStock
表中插入、删除或更新行时自动调整数量值。

您存储此值的原因是什么(如果某个内容以某种方式绕过了您的更新代码,则很容易过时)而不是使用视图(可能是索引视图)哪一个总是有正确的值?为什么不使用触发器?这可能更简单。数量如何在ItemMaster表中求和。是数量的总数还是与特定ID相关的数量。