0

I want to convert this sql code to firebird sql for find working days between two dates:

CREATE FUNCTION [dbo].fn_CountWeekDays
(
@fromdate Datetime,
@todate Datetime
)
RETURNS TABLE AS RETURN
(

 SELECT
(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)
As NoOfWeekDays

)

thanks

4

1 回答 1

1

您当前的 SQL Server 函数是一个表值函数(它返回一个表),Firebird 3(及更早版本)中最接近的等效函数是一个可选择的存储过程:

create or alter procedure CountWeekDays(fromdate timestamp, todate timestamp)
returns (NoOfWeekDays bigint)
as
declare normalizedFrom timestamp;
declare normalizedTo timestamp;
begin
    normalizedFrom = dateadd(-1 * extract(weekday from fromdate) day to fromdate);
    normalizedTo = dateadd(-1 * extract(weekday from todate) day to todate);
    NoOfWeekDays = (DATEDIFF(day, fromdate, todate) + 1)
            -(DATEDIFF(week, normalizedFrom , normalizedTo) * 2)
            -(CASE WHEN extract(weekday from fromdate) = 0 THEN 1 ELSE 0 END)
            -(CASE WHEN extract(weekday from todate) = 6 THEN 1 ELSE 0 END);
    -- Suspend is necessary to make it selectable!
    suspend;
end

星期差的tofrom日期到星期天的标准化是必要的,因为不幸的是datediff(week ...)Firebird 不计算星期,但是两个日期之间有 7 天的周期,所以例如datediff(week, date'2017-07-14', date'2017-07-20')(星期五到下星期四)是 0 ,而不是 1。标准化到一周中的星期日将确保正确计算周差。

一个警告:我只用(小)日期选择测试了它,并将它与 SQL Server 函数的输出进行了比较,我没有用时间组件进行测试,你可能想更彻底地验证它。

鉴于数据的性质,您还可以在 SQL Server 中使用标量函数。标量函数的等价物是PSQL 函数(在 Firebird 3 中引入)

create or alter function fn_CountWeekDays(fromdate timestamp, todate timestamp)
returns bigint
as
declare normalizedFrom timestamp;
declare normalizedTo timestamp;
begin 
    normalizedFrom = dateadd(-1 * extract(weekday from fromdate) day to fromdate);
    normalizedTo = dateadd(-1 * extract(weekday from todate) day to todate);
    return (DATEDIFF(day, fromdate, todate) + 1)
            -(DATEDIFF(week, normalizedFrom , normalizedTo) * 2)
            -(CASE WHEN extract(weekday from fromdate) = 0 THEN 1 ELSE 0 END)
            -(CASE WHEN extract(weekday from todate) = 6 THEN 1 ELSE 0 END);
end

参考:

于 2017-07-15T09:43:36.023 回答