维护一个代理商管理系统,要嵌套查询,绕来绕去,最后差点晕了,突然想到SQL也有自定义函数,于是尝试着用自定义函数来解决困难。
如下,先定义一个函数:
1
create function CheckEvaluateStatus(@contractID varchar(30)) returns bit2
as3
begin4
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 d8
where c.SprID+c.ContractID=@contractID9
and c.JID=d.JID10
and c.Office=d.Office11
if @FW!=''12
begin13
if exists(select top 1 AutoID from eventsheet14
where deptID='FW'15
and contractID=@contractID16
and modifyUser is null)17
return 018
if not exists(select top 1 autoID from eventsheet19
where contractID=@contractID20
and deptID='FW')21
return 022
end23
if @QC!=''24
begin25
if exists(select top 1 AutoID from eventsheet26
where deptID='QC'27
and contractID=@contractID28
and modifyUser is null)29
return 030
if not exists(select top 1 autoID from eventsheet31
where contractID=@contractID32
and deptID='QC')33
return 034
end35
if @EC!=''36
begin37
if exists(select top 1 AutoID from eventsheet38
where deptID='EC'39
and contractID=@contractID40
and modifyUser is null)41
return 042
if not exists(select top 1 autoID from eventsheet43
where contractID=@contractID44
and deptID='EC')45
return 046
end 47
return 1 48
end
调用这个函数的方法,dbo.CheckEvaluateStatus(c.SprID+c.ContractID). 见以下存储过程:
1
alter proc GetUnfinishedContract2
(3
@jobNo varchar(30),4
@startDate datetime,5
@endDate datetime6
)7
as 8
if @jobNo!=''9
begin10
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.RemindLog11
from mContract c,dJobInfo i,dJobDuty d,mSupplier s12
where c.StartDate>@startDate13
and c.EndDate<@endDate14
and c.JID=i.JID15
and i.jobNO=@jobNo16
and d.JID=c.JID 17
and c.Office=d.Office18
and s.SprID=c.SprID19
and dbo.CheckEvaluateStatus(c.SprID+c.ContractID)=020
end 21
else22
begin23
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.RemindLog24
from mContract c,dJobInfo i,dJobDuty d,mSupplier s25
where c.StartDate>@startDate26
and c.EndDate<@endDate27
and c.JID=i.JID28
and d.JID=c.JID 29
and c.Office=d.Office30
and s.SprID=c.SprID31
and dbo.CheckEvaluateStatus(c.SprID+c.ContractID)=032
end33

浙公网安备 33010602011771号