Insert Into One Table 基于另一个
Insert Into One Table based on Another
我在 ssms 中有两个 tables,我希望将其中一个的数据放入另一个,但我不想包含我已经添加的一些数据。
Table 一个是来自特定供应商的数据,它包括一个ID和我想抓取的数量,
Table 两个有来自我所有供应商的组合数据,其中每个产品都有不同的 ID、数量和该数量的单位(我们的一些供应商按件销售,其他供应商销售平方英尺) .
我正在尝试使用此代码:
insert into Table2(DistinctID, Quantity,Units)
Select DistinctID, Pieces, 'Pieces' from Table1
Where DistinctID <> Table1.DistinctID
然而,当我 运行 这个时,没有值被添加到 table。我在想这是因为声明每次都在寻找相同的 Distinct ID,所以我想我会尝试澄清我的 Where 声明:
Where Table2.DistinctID <> Table1.distinctID
除了我这样做的时候,我 运行 进入有关无法绑定来自 table2 的多部分标识符的错误。
我确定有解决方案,但我只是不明白它是什么。有什么建议吗?如果有任何我没有解释清楚的地方,我会很乐意澄清,我是编程游戏的新手
我会尝试 NOT EXISTS 子句
insert into Table2(DistinctID, Quantity, Units)
select t1.DistinctID, t1.Pieces, 'Pieces' from Table1 t1
where not exists
(select null
from table2 t2
where t2.DistinctID = t1.DistinctID)
因为在你的第一次尝试中,你做到了DistinctID <> Table1.DistinctID
。但是 DistinctId
都来自 table1
(并且值永远不会不同于......与它本身)。
在第二次尝试中,Table2
不在 select 部分,因此未知。并不是因为它在 insert
子句中,它在 select
子句中是已知的。
我在 ssms 中有两个 tables,我希望将其中一个的数据放入另一个,但我不想包含我已经添加的一些数据。
Table 一个是来自特定供应商的数据,它包括一个ID和我想抓取的数量,
Table 两个有来自我所有供应商的组合数据,其中每个产品都有不同的 ID、数量和该数量的单位(我们的一些供应商按件销售,其他供应商销售平方英尺) .
我正在尝试使用此代码:
insert into Table2(DistinctID, Quantity,Units)
Select DistinctID, Pieces, 'Pieces' from Table1
Where DistinctID <> Table1.DistinctID
然而,当我 运行 这个时,没有值被添加到 table。我在想这是因为声明每次都在寻找相同的 Distinct ID,所以我想我会尝试澄清我的 Where 声明:
Where Table2.DistinctID <> Table1.distinctID
除了我这样做的时候,我 运行 进入有关无法绑定来自 table2 的多部分标识符的错误。
我确定有解决方案,但我只是不明白它是什么。有什么建议吗?如果有任何我没有解释清楚的地方,我会很乐意澄清,我是编程游戏的新手
我会尝试 NOT EXISTS 子句
insert into Table2(DistinctID, Quantity, Units)
select t1.DistinctID, t1.Pieces, 'Pieces' from Table1 t1
where not exists
(select null
from table2 t2
where t2.DistinctID = t1.DistinctID)
因为在你的第一次尝试中,你做到了DistinctID <> Table1.DistinctID
。但是 DistinctId
都来自 table1
(并且值永远不会不同于......与它本身)。
在第二次尝试中,Table2
不在 select 部分,因此未知。并不是因为它在 insert
子句中,它在 select
子句中是已知的。