insert into select query-multipart identifier无法绑定

时间:2017-01-25 11:55:46

标签: sql sql-server

此查询返回多部分标识符无法绑定

table2.AId and  table1.LId = table2.LId

查询

insert into table1(col1)
select col2 from table2
where table1.AId = table2.AId and  table1.LId = table2.LId;

非常感谢您的帮助

3 个答案:

答案 0 :(得分:3)

您需要在SELECT子句中的FROM中包含所有表格。所以,这在语法上是正确的:

insert into table1(col1)
    select t2.col2
    from table2 t2 join
         table1 t1
         on t1.AId = t2.AId and t1.LId = t2.LId;

但是,您可能打算UPDATE

update t1
    set col1 = t2.col2
    from table1 t1 join
         table2 t2             
         on t1.AId = t2.AId and t1.LId = t2.LId;

这会修改t1中的行。带有insert的版本将只在一列中插入新值,而新值只有。

答案 1 :(得分:1)

您的选择查询不会“知道”插入部分中的表格,因此您应该使用连接:

insert into table1(col1)
select col2 
from table2
inner join table1 on table1.AId = table2.AId and  table1.LId = table2.LId;

但是,我怀疑你正在寻找更新,而不是插入:

update t1
set col1 = t2.col2 
from table1 t1 
inner join table2 t2 on t1.AId = t2.AId and  t1.LId = t2.LId;

答案 2 :(得分:1)

缺少join条件

insert into table1(col1)
    select t2.col2
    from table2 t2 join
         table1 t1
         on t1.AId = t2.AId and t1.LId = t2.LId;