我需要将Firebird存储过程中的 current_date 交换为相当于StartOfTheDay和EndOfTheDay的Delphi。
Delphi的StartOfTheDay返回18.08.2017:00.00.00.001,EndOfTheDay返回18.08.2017:23.59.59.999。
如何在Firebird中执行此操作?
答案 0 :(得分:4)
您可以编写如下命令:
SELECT DATEADD(MILLISECOND, 1, CAST(CURRENT_DATE AS TIMESTAMP)) FROM RDB$DATABASE
在程序中它可以是:
CREATE PROCEDURE MyProcedure
AS
DECLARE VARIABLE DayStart TIMESTAMP;
BEGIN
DayStart = DATEADD(MILLISECOND, 1, CAST(CURRENT_DATE AS TIMESTAMP));
...
END
它将DATE值转换为TIMESTAMP(因为DATEADD函数对输入数据类型敏感),然后向该值添加1毫秒。对于今天你应该得到这个(但我认为它不会与Delphi函数结果相匹配):
18.08.2017, 00:00:00.001
与当天的开始类似,您可以编写此命令以结束当天:
SELECT DATEADD(MILLISECOND, -1, CAST(CURRENT_DATE + 1 AS TIMESTAMP)) FROM RDB$DATABASE
在程序中:
CREATE PROCEDURE MyProcedure
AS
DECLARE VARIABLE DayEnd TIMESTAMP;
BEGIN
DayEnd = DATEADD(MILLISECOND, -1, CAST(CURRENT_DATE + 1 AS TIMESTAMP));
...
END
这个为给定DATE添加1天,然后转换为TIMESTAMP并从中减去1毫秒。今天它应该返回(与上面提到的Delphi函数匹配):
18.08.2017, 23:59:59.999
如果您的输入为TIMESTAMP类型且指定了时间部分,则首先转换为DATE以删除TIME部分。例如,从TIMESTAMP值开始获取日期:
SELECT DATEADD(MILLISECOND, 1, CAST(CAST(CURRENT_TIMESTAMP AS DATE) AS TIMESTAMP)) FROM RDB$DATABASE
或类似地在存储过程中:
CREATE PROCEDURE MyProcedure
AS
DECLARE VARIABLE DayEnd TIMESTAMP;
DECLARE VARIABLE DayStart TIMESTAMP;
DECLARE VARIABLE DateTime TIMESTAMP;
BEGIN
DateTime = CURRENT_TIMESTAMP; -- this has time portion if not executed at midnight
DayStart = DATEADD(MILLISECOND, 1, CAST(CAST(DateTime AS DATE) AS TIMESTAMP));
DayEnd = DATEADD(MILLISECOND, -1, CAST(CAST(DateTime AS DATE) + 1 AS TIMESTAMP));
...
END
答案 1 :(得分:0)
首先,请注意Delphi将StartOfTheDay函数实现为:
function StartOfTheDay(const AValue: TDateTime): TDateTime;
begin
Result := Trunc(AValue);
end;
这意味着它不会返回18.08.2017:00.00.00.001但是18.08.201700.00.00.000,女巫是真的。
在Firebird 3.0及更高版本中,您可以将StartOfTheDay和EndOfTheDay例程实现为函数:
create or alter function STARTOFTHEDAY (
STAMP timestamp)
returns timestamp
as
begin
return cast(STAMP as date);
end
和
create or alter function ENDOFTHEDAY (
STAMP timestamp)
returns timestamp
as
begin
return dateadd(millisecond, -1, cast(cast(STAMP as date) + 1 as timestamp));
end
在旧版本中,在存储过程中嵌入相同的代码。
测试和使用:
select
-- Date type
STARTOFTHEDAY(current_date),
ENDOFTHEDAY(current_date),
-- Timestamp type
STARTOFTHEDAY(current_timestamp),
ENDOFTHEDAY(current_timestamp)
from RDB$DATABASE
今天的结果:
STARTOFTHEDAY: 22.09.2017 00:00:00.000
ENDOFTHEDAY: 22.09.2017 23:59:59.999