在存储过程中查询一批记录,然后跟一个表比较,如果存在就跳过,否则插入?怎么样做?
我在一个存储过程,下面是读取一个记录
SELECT max(createtime) , storage.bumen as 部门, product_id , storage.gongyi as 工艺 , product.product as 产品名称 FROM storage INNER JOIN product ON storage.product_id = product.ID group by product.product,storage.gongyi , product_id ,storage.bumen having sum(storage.product_ru-storage.product_chu-storage.baofei)=0 order by product.product
我还有一个表(A),其中有字段
时间,部门,工艺,product_id 。
读取记录后,每次可能200条记录左右。
需要循环跟表A中的部门,工艺,时间,product_id 比较。四者条件相同则条过。否则则插入一条记录。
可以实现吗????
麻烦高手详细写出来?
问题点数:50、回复次数:6Top
1 楼hdslah()回复于 2003-11-04 20:35:55 得分 0
if not exists (select * from 存儲過程表 a inner join 另一表 b on a.比較字段=b.比較字段)
begin
insert table
end
Top
2 楼zjcxc(邹建)回复于 2003-11-04 20:36:20 得分 50
insert into A(时间,部门,工艺,product_id)
select 时间,部门,工艺,product_id
from(
SELECT max(createtime) as 时间
,storage.bumen as 部门
,product_id
,storage.gongyi as 工艺
,product.product as 产品名称
FROM storage INNER JOIN product
ON storage.product_id = product.ID
group by product.product,storage.gongyi , product_id ,storage.bumen
having sum(storage.product_ru-storage.product_chu-storage.baofei)=0
) a
where not exists(select 1 from A where 时间=a.时间,部门=a.部门,工艺=a.工艺,product_id=a.product_id)
Top
3 楼zjcxc(邹建)回复于 2003-11-04 20:38:52 得分 0
--照理解,你是想将查询结果在A表中不存在的插入A表吧.
--或者
insert into A(时间,部门,工艺,product_id)
select 时间,部门,工艺,product_id
from(
SELECT max(createtime) as 时间
,storage.bumen as 部门
,product_id
,storage.gongyi as 工艺
,product.product as 产品名称
FROM storage INNER JOIN product
ON storage.product_id = product.ID
group by product.product,storage.gongyi , product_id ,storage.bumen
having sum(storage.product_ru-storage.product_chu-storage.baofei)=0
) a left join A b on b.时间=a.时间,b.部门=a.部门,b.工艺=a.工艺,b.product_id=a.product_id
where b.时间 is null and b.部门 is null and b.工艺 is null and b.product_id is null
Top
4 楼j9988(j9988)回复于 2003-11-04 20:40:31 得分 0
insert tabA(......) select * from (
SELECT max(createtime) as 时间, storage.bumen as 部门, product_id , storage.gongyi as 工艺 , product.product as 产品名称 FROM storage INNER JOIN product ON storage.product_id = product.ID group by product.product,storage.gongyi , product_id ,storage.bumen having sum(storage.product_ru-storage.product_chu-storage.baofei)=0 --order by product.product
) A where not exists (select 1 from tabA where 部门=A.部门,工艺=A.工艺,时间=A.时间,product_id=A.product_id)
Top
5 楼j9988(j9988)回复于 2003-11-04 20:41:06 得分 0
天! 这么快!Top
6 楼cnzjsy(zhuang)回复于 2003-11-04 20:50:25 得分 0
我去试一下Top




