【问题标题】:Update a table using data of other table使用其他表的数据更新表
【发布时间】:2011-06-29 03:46:28
【问题描述】:

我正在使用 Visual Studio 2008 和 Sql Server 2005

我想使用其他表中的值更新一个表 我已经写了一个查询,但它给出了错误

“无法将值 NULL 插入 'Quantity' 列,表 'Stationarymgmt.dbo.Item_Master';列不允许空值。更新失败。”

临时表有以下列 项目代码, 数量, 成本 , 姓名 , 说明,

Item_Master 表有以下列 项目代码, 姓名, 说明, 成本 , 数量,

查询是

    UPDATE Item_Master,temp
 SET Item_Master.Quantity = Item_Master.Quantity - temp.Quantity where Item_Master.Item_Code = temp.Item_Code

请帮帮我

【问题讨论】:

    标签: .net sql vb.net sql-server-2005


    【解决方案1】:

    您可以使用 SQL Server 的 update ... from 重写它:

    UPDATE  im
    SET     Quantity = im.Quantity - temp.Quantity
    FROM    Item_Master im
    JOIN    temp
    ON      im.Item_Code = temp.Item_Code
    WHERE   temp.Quantity is not null
    

    where 条件应从temp 中过滤掉缺少数量的行。

    【讨论】:

      【解决方案2】:

      记住 Value - NULL = NULL 与 'String' + NULL = NULL 的方式相同

      所以

      UPDATE Item_Master,temp
      SET Item_Master.Quantity = Item_Master.Quantity - ISNULL(temp.Quantity, 0) 
      WHERE Item_Master.Item_Code = temp.Item_Code
      

      UPDATE Item_Master,temp
      SET Item_Master.Quantity = Item_Master.Quantity - temp.Quantity 
      WHERE Item_Master.Item_Code = temp.Item_Code
      AND temp.Quanity IS NOT NULL
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-11
        • 2021-06-26
        • 1970-01-01
        • 2019-01-16
        • 1970-01-01
        • 1970-01-01
        • 2021-05-04
        • 1970-01-01
        相关资源
        最近更新 更多