-- tf_wfget_appvr_records
create function [dbo].[tf_wfget_appvr_records] ( @cls_id int, @start_date datetime, @end_date datetime, @approver_id int, @co_id varchar( 5))
returns @wfapp_approver_status
table
( app_recgid bigint,
app_status varchar(1),
app_status_desc varchar( 80)
)
as
begin
insert into @wfapp_approver_status
( app_recgid, app_status, app_status_desc)
select a.recgid, a.status, p.action
from cm_wfapp a
inner join cm_process p on a.proc_id = p.recgid
where a.co_id = @co_id and a.cls_id = @cls_id
and a.apply_date between @start_date and @end_date
and a.approver_id = @approver_id
-- insert others from cm_wftrn
insert into @wfapp_approver_status
( app_recgid, app_status, app_status_desc)
select distinct a.recgid, a.status, p.action
from cm_wftrn c
inner join cm_process p on c.proc_id = p.recgid and p.action is not null
inner join cm_wfapp a on a.recgid = c.wfapp_id
where a.co_id = @co_id and a.cls_id = @cls_id
and a.apply_date between @start_date and @end_date
and c.wfapp_id not in ( select app_recgid from @wfapp_approver_status )
and c.appr_id = @approver_id
return
end
GO
它包含NOT IN约束,这需要花费大量时间从数据库中提取结果。 数据库显然非常庞大。
如何优化此查询? 有没有办法用NOT IN优化查询(选择...)?
请帮助谢谢。
答案 0 :(得分:2)
将您的NOT IN
替换为NOT EXISTS
运算符,如下所示....
insert into @wfapp_approver_status
( app_recgid, app_status, app_status_desc)
select distinct a.recgid, a.status, p.action
from cm_wftrn c
inner join cm_process p on c.proc_id = p.recgid and p.action is not null
inner join cm_wfapp a on a.recgid = c.wfapp_id
where a.co_id = @co_id and a.cls_id = @cls_id
and a.apply_date between @start_date and @end_date
and c.appr_id = @approver_id
and not exists ( select 1
from @wfapp_approver_status
WHERE c.wfapp_id = app_recgid)