【问题标题】:How to insert a table conditionally如何有条件地插入表格
【发布时间】:2013-01-12 04:00:12
【问题描述】:

我有一个表 tbl1(col1, col2, col3, ..., coln),col1 和 col2 一起是主键。我正在尝试使用以下查询将记录从临时表 #t 插入到 tbl1

insert into tbl1(col1, col2, col3, ..., colm)
select #t.col1, #t.col2, #t.col3, ..., #t.colm
from #t where col2 <> #t.col2

但是,我收到以下错误,无法绑定多部分标识符“tblDailyBalanceHistory.BalanceDate”。如何修复我的查询?

【问题讨论】:

  • 它说它无法弄清楚该表中的那一列来自哪里。这是我们可以提供的尽可能多的帮助,因为您没有发布实际的 sql,这会导致错误。
  • 我的错,错误信息应该是 The multi-part identifier "tbl1.col2" could not be bound。但我认为这不会影响你理解我的问题。有人给了我正确的答案。
  • 那他们一定比我聪明。 :)

标签: sql-server-2008 select insert


【解决方案1】:

我认为您的问题在于您的 WHERE 标准。你不能说 col2 #t.col2 因为 col2 还没有被定义。

试试这样的:

insert into tbl1(col1, col2, col3, ..., colm)
select #t.col1, #t.col2, #t.col3, ..., #t.colm
from #t 
   left join tbl1 on #t.col2 = tbl1.col2
where tbl1.col2 is null

祝你好运。

【讨论】:

  • 谢谢,我只需要做一个小调整,当我加入两个表时,我必须同时加入 col1 和 col2,因为它们是组合的主键。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-19
  • 1970-01-01
  • 2012-11-25
  • 2016-08-03
相关资源
最近更新 更多