我有一个用户定义的标量函数,称为fn_CountWeekDays,它接受2个参数startdate和enddate并返回一个整数值。该函数基本上计算开始日期和结束日期之间的工作日。
功能代码:
CREATE FUNCTION [dbo].[fn_CountWeekDays]
(
@fromdate Datetime,
@todate Datetime
)
RETURNS INT AS
Begin
Declare @NoOfWeekDays int
Set @NoOfWeekDays = (DATEDIFF(dd, @fromdate, @todate) + 1)
-(DATEDIFF(wk, @fromdate, @todate) * 2)
-(CASE WHEN DATENAME(dw, @fromdate) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, @todate) = 'Saturday' THEN 1 ELSE 0 END)
Return @NoOfWeekDays
End
如何在case语句中调用该函数并同时将其与另一个整数值进行比较?
以下是我的询问:
select
Case
when Priority in ('1 - Critical','2 - High') and fn_CountWeekDays(Opened,Closed) <= 3 and ProblemState = 'Closed/Resolved' then 1 else 0
End as RCA_KPI_P1_P2_Met,
Case
when Priority = '3 - Moderate' and fn_CountWeekDays(Opened,Closed) <= 5 and ProblemState = 'Closed/Resolved' then 1 else 0
End as RCA_KPI_P3_Met
from v_Problem
答案 0 :(得分:0)
你的函数是一个内联表值函数而不是标量函数吗?如果是这样,那么您可能需要在子查询中使用它,或者像cross apply()
那样使用它:
select
case
when Priority in ('1 - Critical', '2 - High')
and w.WeekDays <= 3
and ProblemState = 'Closed/Resolved'
then 1
else 0
end as RCA_KPI_P1_P2_Met
, case
when Priority = '3 - Moderate'
and w.WeekDays <= 5
and ProblemState = 'Closed/Resolved'
then 1
else 0
end as RCA_KPI_P3_Met
from v_Problem
cross apply tvf_CountWeekDays(Opened,Closed) w
如果你的函数不是一个内联表值函数,那你应该写一个像这样的函数:
create function [dbo].[tvf_CountWeekDays] (@fromdate datetime,@todate datetime)
returns table with schemabinding as return (
select
WeekDays = (datediff(day, @fromdate, @todate) + 1)
- (datediff(week, @fromdate, @todate) * 2)
- (case when datename(weekday, @fromdate) = 'Sunday' then 1 else 0 end)
- (case when datename(weekday, @todate) = 'Saturday' then 1 else 0 end)
)
go
参考: