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

后端 未结 7 1378
情话喂你
情话喂你 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:44

    The simplest form is always the best

    CREATE FUNCTION [dbo].[age](@set varchar(10))
    RETURNS TABLE
    AS RETURN
    SELECT * from player
    where ((@set = 'tall' and height > 180)
       or (@set = 'average' AND height >= 155 and height <=175)
       or (@set = 'low' AND height < 155))
    GO
    

    This form is called INLINE table function, which means SQL Server is free to expand it to join player directly to other tables in-line of a greater query, making it perform infinitely1 better than a multi-statement table valued function.

    You may prefer this though, so that your ranges are complete (you have a gap between 175 and 180)

    where ((@set = 'tall' and height > 180)
       or (@set = 'average' AND height >= 155 and height <= 180)
       or (@set = 'low' AND height < 155))
    

    SQL Server takes care of short circuiting the branches when the variable @set is parsed.

    1 exaggeration, but only slightly

提交回复
热议问题