我想编写一个返回datediff的函数,而忽略SQL Server上的周末。 是否可以将间隔作为我的用户定义函数的参数传递,如下所示? SQL Server说“为datediff指定了无效的参数1。”
CREATE FUNCTION [dbo].[DATEDIFFWD](@interval varchar(2), @ini datetime, @end datetime)
RETURNS int
AS
BEGIN
DECLARE @output int
SET @output = DATEDIFF(@interval, @ini, @end)
IF (@interval = 'hh') SET @output = @output - (DATEDIFF(WK, @ini, @end) * 48)
IF (@interval = 'dd') SET @output = @output - (DATEDIFF(WK, @ini, @end) * 2)
RETURN @output
END
答案 0 :(得分:4)
您可以将其重写为:
CREATE FUNCTION [dbo].[DATEDIFFWD](@interval varchar(2),
@ini datetime, @end datetime)
RETURNS int
AS
BEGIN
RETURN (SELECT CASE @interval
WHEN 'hh' THEN DATEDIFF(hh, @ini, @end) - ((DATEDIFF(WK, @ini, @end) * 48))
WHEN 'dd' THEN DATEDIFF(dd, @ini, @end) - ((DATEDIFF(WK, @ini, @end) * 2))
END
);
END
请注意,scalar function could be inlined starting from SQL Server 2019
为了获得更好的性能,我将改用表函数:
CREATE FUNCTION [dbo].[DATEDIFFWD](@interval varchar(2),
@ini datetime, @end datetime)
RETURNS TABLE
AS
RETURN (
SELECT CASE @interval
WHEN 'hh' THEN DATEDIFF(hh, @ini, @end) - ((DATEDIFF(WK, @ini, @end) * 48))
WHEN 'dd' THEN DATEDIFF(dd, @ini, @end) - ((DATEDIFF(WK, @ini, @end) * 2))
END AS r
);
答案 1 :(得分:1)
DATEDIFF
will not accept user-defined变量等效于DATEPART
。您必须在动态SQL中将其串联起来,或使用其他逻辑将变量分隔到DATEDIFF
之外。另外,我不会在varchar(2)
上使用@interval
主要是因为it's a bad habit one should kick.。