相关NOT EXISTS错误:无法绑定多部分标识符“xxx”

时间:2013-08-14 18:00:36

标签: sql-server-2008-r2

update IQAlarm
set IQAD=GETDATE(),AD=AD+1
where exists (select CPC from Inquiry where Inquiry.IQST='ooo' 
  and DATEDIFF(DAY,GETDATE(),Inquiry.QDL)<=3 and Inquiry.CPC = IQAlarm.CPC);

insert into IQAlarm (CPC)  
select CPC from Inquiry   
where not exists (select CPC from Inquiry where Inquiry.IQST='ooo' 
and DATEDIFF(DAY,GETDATE(),Inquiry.QDL)<=3 and Inquiry.CPC = **IQAlarm.CPC**);

更新工作正常,但插入会产生此错误:

  

无法绑定多部分标识符“IQAlarm.CPC”。

1 个答案:

答案 0 :(得分:1)

你的第一次更新应该有一个FROM条款来支持相关性(但是我没有感到震惊它没有一个 - 这不是我写的方式。)

UPDATE IQAlarm
set IQAD=GETDATE(),AD=AD+1
FROM IQAlarm -- <----- you need this
where exists (select CPC from Inquiry 
  where Inquiry.IQST='ooo' and DATEDIFF(DAY,GETDATE(),Inquiry.QDL)<=3 
  and Inquiry.CPC = IQAlarm.CPC);

而且我认为你的第二个都搞砸了。也许这就是你的意思:

insert into IQAlarm (CPC)
  select CPC from Inquiry
  where IQST='ooo' 
   and DATEDIFF(DAY,GETDATE(),Inquiry.QDL)<=3 
  and not exists (SELECT 1 FROM IQAlarm WHERE CPC = Inquiry.CPC);