TSQL - If..Else statement inside Table-Valued Functions - cant go through

后端 未结 7 1461
情话喂你
情话喂你 2021-02-07 02:51

Before posting I have read few articles about developing USD functions, but have not encountered solutions for my problem... which is as follows:

I have a very simple da

7条回答
  •  半阙折子戏
    2021-02-07 03:49

    You were close. Using a multi-statement table-valued function requires the return table to be specified and populated in the function:

    CREATE FUNCTION [dbo].[age](@set varchar(10))
    RETURNS @Players TABLE
    (
        -- Put the players table definition here
    ) 
    AS
    BEGIN
    
        IF  (@set = 'tall')
             INSERT INTO @Players SELECT * from player where height > 180
    
        ELSE IF (@set = 'average')
             INSERT INTO @Players SELECT * from player where height >= 155 and height <=175
    
        ELSE IF (@set = 'low')
             INSERT INTO @Players SELECT * from player where height < 155
    
        RETURN -- @Players (variable only required for Scalar functions)
    
    END
    

    I would recommend using an inline TVF as Richard's answer demonstrates. It can infer the table return from your statement.

    Note also that a multi-statement and inline TVFs are really quite different. An inline TVF is less of a black-box to the optimizer and more like a parametrized view in terms of the optimizer being able to rearrange things with other tables and views in the same execution plan.

提交回复
热议问题