TSQL 函数递归
我有这个:
CREATE FUNCTION [dbo].[udf_SLA_AdjustDateTimeForBusinessHours]
(
@DateTime DateTime
)
RETURNS DateTime
AS
BEGIN
DECLARE @AdjustedDate DateTime;
If dbo.udf_SLA_IsBusinessDay(@DateTime) = 1
BEGIN
IF dbo.udf_SLA_IsWithinBusinessHours(@DateTime) = 1
SET @AdjustedDate = @DateTime
Else
BEGIN
IF dbo.udf_TimeOnly(@DateTime) < dbo.udf_Time(8,0,0)
SET @AdjustedDate = dbo.udf_DateOnly(@DateTime) + dbo.udf_Time(8, 0, 0)
ELSE
SET @AdjustedDate = dbo.udf_SLA_AdjustDateTimeForBusinessHours(dbo.udf_DateOnly(@DateTime) + 1 + dbo.udf_Time(8, 0, 0))
END
END
RETURN @AdjustedDate
END
这是有趣的部分:
SET @AdjustedDate = dbo.udf_SLA_AdjustDateTimeForBusinessHours(dbo.udf_DateOnly(@DateTime) + 1 + dbo.udf_Time(8, 0, 0))
我想从函数本身调用该函数。现在,执行该代码分支时我得到的只是 NULL。这是使用 CTE 的地方吗?
udf_SLA_IsBusinessDay 和 udf_SLA_IsWithinBusinessHours 是不言自明的。 udf_DateOnly、udf_TimeOnly、udf_Time 等来自此处。
I have this:
CREATE FUNCTION [dbo].[udf_SLA_AdjustDateTimeForBusinessHours]
(
@DateTime DateTime
)
RETURNS DateTime
AS
BEGIN
DECLARE @AdjustedDate DateTime;
If dbo.udf_SLA_IsBusinessDay(@DateTime) = 1
BEGIN
IF dbo.udf_SLA_IsWithinBusinessHours(@DateTime) = 1
SET @AdjustedDate = @DateTime
Else
BEGIN
IF dbo.udf_TimeOnly(@DateTime) < dbo.udf_Time(8,0,0)
SET @AdjustedDate = dbo.udf_DateOnly(@DateTime) + dbo.udf_Time(8, 0, 0)
ELSE
SET @AdjustedDate = dbo.udf_SLA_AdjustDateTimeForBusinessHours(dbo.udf_DateOnly(@DateTime) + 1 + dbo.udf_Time(8, 0, 0))
END
END
RETURN @AdjustedDate
END
This is the interesting part:
SET @AdjustedDate = dbo.udf_SLA_AdjustDateTimeForBusinessHours(dbo.udf_DateOnly(@DateTime) + 1 + dbo.udf_Time(8, 0, 0))
I want to call the function from the function itself. As it is now, all I get is NULL when executing that branch of the code. Is this where a CTE is used?
udf_SLA_IsBusinessDay and udf_SLA_IsWithinBusinessHours are self explanatory. udf_DateOnly, udf_TimeOnly, udf_Time etc come from here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您在非工作日时缺少 ELSE 子句。
该功能迎合了您所追求的业务逻辑。
我还将
dbo.udf_Time(8, 0, 0)
更改为'08:00'
,无需该函数也能正常工作。如果我可以打扰的话,函数
udf_DateOnly
可以更简单I think you are missing an ELSE clause when it is not on a business day.
This function caters for the business logic you are after.
I also made changes to
dbo.udf_Time(8, 0, 0)
to be just'08:00'
which works as well without the function.If I may intrude, the function
udf_DateOnly
could be simplerdateonly 函数可以更简单。
试试这个:
通过这种方式,您可以从日期时间值中提取日期部分。
The function dateonly can be even simpler.
Try this:
This way you cast extract the date part from a datetime value.