2017-05-31 45 views
0

我有一個用戶定義的標量函數,名爲fn_CountWeekDays,它接受2個參數startdate和enddate並返回一個整數值。該功能基本上計算開始和結束日期之間的平日的no。在case語句中使用標量函數

功能代碼:

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

這不起作用?它看起來應該是 – nimdil

+2

我希望這也可以工作。從性能角度來看,將函數重寫爲表值函數會更好 – HoneyBadger

+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 

參考:

+0

我的函數是標量值。我應該使用您建議的查詢嗎? –