用内联函数替换标量函数

Replacement for scalar function by inline function

我有一个当前使用标量函数的过程,在 select 语句中描述了两次 below.Is 当我们处理数百万 [=14] 时,将其替换为内联函数在性能上更好=] 所以应该是什么

CREATE FUNCTION getcategory
(
    @shopping_store CHAR(4),
    @cart_type      CHAR(2),
    @category_type  INT,
    @index_cat_type INT
)
RETURNS INT
BEGIN
    IF @shopping_store IN ('1111','1222','3222') AND @cart_type in ('120')
        RETURN -@category_type
    ELSE IF @shopping_store IN ('4333','54322') AND @cart_type IN ('120')
        RETURN @index_cat_type
    ELSE
    BEGIN
        IF @shopping_store IN ('32214','5432','5654')
            RETURN @category_type
        ELSE
            RETURN -@index_cat_type
    END

    RETURN @category_type
END

所有这些 IF ELSE 都可以转换为单个 case 表达式。然后,您可以将此标量函数转换为内联 table 值函数。当您声明您有数百万行时,这样做的性能优势应该相当可观。我还冒昧地将 @cart_type 更改为 char(4),因为正如 GarethD 指出的那样,它甚至不能包含“120”。我在要负数的时候也用显式乘法,因为太容易漏掉一个 - 一开始,乘以负数1就很清楚了。

CREATE FUNCTION getcategory
(
    @shopping_store CHAR(4),
    @cart_type      CHAR(4),
    @category_type  INT,
    @index_cat_type INT
)
RETURNS TABLE as RETURN
    select case 
        when @shopping_store IN ('1111','1222','3222') AND @cart_type in ('120') 
            then -1 * @category_type
        when @shopping_store IN ('4333','54322') AND @cart_type IN ('120')
            then @index_cat_type
        when @shopping_store IN ('32214','5432','5654')
            then @category_type
        ELSE
            -1 * @index_cat_type
    END as CategoryType