使用Insert Into和Inner Join插入

时间:2017-03-09 10:34:52

标签: sql-server

我正在从一个表的列中插入数据行到另一个表的列。这是我完成的工作:

Insert into [Inventory](Cost)
Select cast(a.[CCost] as numeric(18,6)) from [InventoryTemp] as a 
Inner join [Inventory] as b on a.[ID] = b.[ID]

我的[Inventory]表中有10000行数据(ID列已填满),但执行上述查询时,Cost数据从10001开始直到20000。

Inventory                      InventoryTemp
ID        Cost                 ID         Cost
1                              1          3.12
3                              3          9.90
18                             18         8.80

我想要的结果

Inventory
ID         Cost
1          3.12
3          9.90
18         8.80

3 个答案:

答案 0 :(得分:1)

如果我已正确阅读您的问题,我认为您正在尝试根据InventoryTemp表中的值更新Inventory表中的cost列的值。

因此,您希望执行UPDATE命令而不是INSERT。

这方面的一个例子是:

UPDATE
    Inventory
SET
    Inventory.Cost = InventoryTemp.Cost
FROM
    Inventory
INNER JOIN 
    InventoryTemp 
ON 
    Inventory.ID = InventoryTemp.ID

有关详细信息,请参阅此问题:How do I UPDATE from a SELECT in SQL Server?

答案 1 :(得分:0)

您需要使用UPDATE i SET [Cost] = it.[Cost] FROM [Inventory] i INNER JOIN [InventoryTemp] it ON i.ID = it.ID 而不是“INSERT'

var Person = function(firstAndLast) {
    var self = this;
    this.getFirstName = function(){
      var first = self.firstName || (function(){
        return firstAndLast.split(' ')[0];

      })();
      return first;
    };
    this.getLastName = function(){
      var last = self.lastName || (function(){
        return firstAndLast.split(' ')[1];

      })();
      return last;
    };
    this.getFullName = function(){
      var full = self.fullName || (function(){
        var first = firstAndLast.split(' ')[0];
        var last = firstAndLast.split(' ')[1];
        return first + " " + last;
      })();
      return full;
    };
    this.setFirstName = function(first){
      self.firstName = first;
      console.log('first name is now: ' + self.firstName);
    };
    this.setLastName = function(last){
      self.lastName = last;
      console.log('last name is now: ' + self.lastName);
    };
    this.setFullName = function(firstAndLast){
      self.fullName = firstAndLast;
      console.log('full name is now: ' + self.fullName);
    };
};

答案 2 :(得分:0)

尝试使用更新。

UPDATE b
SET b.Cost = a.Cost
FROM
[InventoryTemp] as a 
Inner join [Inventory] as b on a.[ID] = b.[ID]