【问题标题】:Update SQL Server table with content from another table [duplicate]使用另一个表中的内容更新 SQL Server 表[重复]
【发布时间】:2016-03-02 20:12:16
【问题描述】:

我需要用另一个 SQL Server 表的内容填充。

我有一张表,Document Items,其中包含(比如说)VendorPartNumberUnitCost 列。

然后我有另一张桌子,PO Items,有VendorPartNumberUnitCost

我需要怎么做才能将相关列内容从DocumentItems 获取到 PO 项中?

【问题讨论】:

  • 您通过什么方式将 [Document Item] 与哪个 [PO Item] 关联起来?
  • 复制你的帖子标题,粘贴到谷歌,你的答案就在首页了。

标签: sql sql-server


【解决方案1】:
update dbo.[PO Items]

set 
    VendorPartNumber = di.VendorPartNumber,
    UnitCost = di.UnitCost
from DocumentItems di 

where [PO Items].[{key column name}] = di.[{key column name}]

【讨论】:

    【解决方案2】:

    如果是一次性操作:

    如果 Part Oder Number 是两个表中的唯一键,您可以使用源表中的 sub select 语句并将值设置为第二个表。

    例如:

    update PO Items 
    set VendorPartNumber = (select VendorPartNumber 
                            from Document Items 
                            where partOrdernumer = ?), 
        UnitCost = (select UnitCost 
                    from Document Items 
                    where partOrdernumer = ?) 
    where partOrdernumer = ?
    

    否则使用触发器来更新第二个表。

    【讨论】:

      【解决方案3】:

      你可以试试:

      insert into POItems (VendorPartNumber, UnitCost) values (select VendorPartNumber, UnitCost from DocumentItems); 
      

      如果需要,可以添加 where 子句。

      【讨论】:

        猜你喜欢
        • 2019-04-16
        • 2021-11-12
        • 1970-01-01
        • 2013-03-11
        • 2021-02-19
        • 2019-05-31
        • 1970-01-01
        • 2017-05-31
        • 2019-08-10
        相关资源
        最近更新 更多