通过DATEDIFF间隔作为用户定义的函数参数?

时间:2018-12-20 19:40:14

标签: sql-server tsql user-defined-functions

我想编写一个返回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

2 个答案:

答案 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

db<>fiddle demo

为了获得更好的性能,我将改用表函数:

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.