您当前的 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
星期差的to和from日期到星期天的标准化是必要的,因为不幸的是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
参考: