维护一个代理商管理系统,要嵌套查询,绕来绕去,最后差点晕了,突然想到SQL也有自定义函数,于是尝试着用自定义函数来解决困难。
如下,先定义一个函数:

Custom Function Code
1
create function CheckEvaluateStatus(@contractID varchar(30)) returns bit
2
as
3
begin
4
declare @FW varchar(30)
5
declare @QC varchar(30)
6
declare @EC varchar(30)
7
select @FW=FW,@QC=QC,@EC=EC from mContract c,dJobDuty d
8
where c.SprID+c.ContractID=@contractID
9
and c.JID=d.JID
10
and c.Office=d.Office
11
if @FW!=''
12
begin
13
if exists(select top 1 AutoID from eventsheet
14
where deptID='FW'
15
and contractID=@contractID
16
and modifyUser is null)
17
return 0
18
if not exists(select top 1 autoID from eventsheet
19
where contractID=@contractID
20
and deptID='FW')
21
return 0
22
end
23
if @QC!=''
24
begin
25
if exists(select top 1 AutoID from eventsheet
26
where deptID='QC'
27
and contractID=@contractID
28
and modifyUser is null)
29
return 0
30
if not exists(select top 1 autoID from eventsheet
31
where contractID=@contractID
32
and deptID='QC')
33
return 0
34
end
35
if @EC!=''
36
begin
37
if exists(select top 1 AutoID from eventsheet
38
where deptID='EC'
39
and contractID=@contractID
40
and modifyUser is null)
41
return 0
42
if not exists(select top 1 autoID from eventsheet
43
where contractID=@contractID
44
and deptID='EC')
45
return 0
46
end
47
return 1
48
end
调用这个函数的方法,dbo.CheckEvaluateStatus(c.SprID+c.ContractID). 见以下存储过程:

Process Code
1
alter proc GetUnfinishedContract
2
(
3
@jobNo varchar(30),
4
@startDate datetime,
5
@endDate datetime
6
)
7
as
8
if @jobNo!=''
9
begin
10
select i.jobNo,i.jobWave, i.jobType,i.Research,i.Office,d.FW,d.QC,d.EC,c.SprID+c.ContractID as CTRID,c.Office,c.startDate,c.endDate,c.Office as OFFICEIC,c.RemindLog
11
from mContract c,dJobInfo i,dJobDuty d,mSupplier s
12
where c.StartDate>@startDate
13
and c.EndDate<@endDate
14
and c.JID=i.JID
15
and i.jobNO=@jobNo
16
and d.JID=c.JID
17
and c.Office=d.Office
18
and s.SprID=c.SprID
19
and dbo.CheckEvaluateStatus(c.SprID+c.ContractID)=0
20
end
21
else
22
begin
23
select i.jobNo,i.jobWave, i.jobType,i.Research,i.Office,d.FW,d.QC,d.EC,c.SprID+c.ContractID as CTRID,c.Office,c.startDate,c.endDate,c.OFFICE as OFFICEIC,c.RemindLog
24
from mContract c,dJobInfo i,dJobDuty d,mSupplier s
25
where c.StartDate>@startDate
26
and c.EndDate<@endDate
27
and c.JID=i.JID
28
and d.JID=c.JID
29
and c.Office=d.Office
30
and s.SprID=c.SprID
31
and dbo.CheckEvaluateStatus(c.SprID+c.ContractID)=0
32
end
33