我如何更新不重复的记录?

时间:2017-11-23 03:57:25

标签: sql sql-server

我只是尝试更新不重复的记录,但语法没有通过,它不起作用

update #tempresult set prod_add=product.prod_made from product 
where (dep_no,prod_no,batch_no) not in  
(select dep_no ,prod_no ,batch_no  from #tempresult
group by dep_no ,prod_no ,batch_no having count(*)>1)

tempresult临时表语法是

create table #tempresult
(
  dep_no char(16) not null,
 prod_no char(8) not null,
 batch_no char(12) not null,
 prod_add char(50) not null,
 dep_date datetime null,
 dep_num numeric(9,3) null,
 inv_num numeric(9,3) null,
 lest_num numeric(9,3) null,
  buy_price numeric(12,6) null ,
 row_index numeric(16, 0) IDENTITY(1,1) not null ,
 primary key(dep_no,prod_no,batch_no,prod_add)
 )

谢谢

1 个答案:

答案 0 :(得分:0)

尝试以下方法(虽然不是一个优雅的解决方案):

update t set prod_add = 
                    (
                       select prod_made 
                       from product p
                       where p.dep_no+'-'+p.prod_no+'-'+p.batch_no not in 
                       (select dep_no+'-'+prod_no+'-'+batch_no  from #tempresult
                       group by dep_no ,prod_no ,batch_no having count(*)>1)
                    )
from #tempresult t
 where dep_no+'-'+prod_no+'-'+batch_no not in 
    (select dep_no+'-'+prod_no+'-'+batch_no  from #tempresult
    group by dep_no ,prod_no ,batch_no having count(*)>1)

感谢。