使用CASE的SQL用户定义函数 - 请完善它

时间:2012-04-19 16:21:35

标签: sql-server sql-server-2005

您能否建议我改进下面的查询。

 ALTER FUNCTION GetTemplate_Lookup_id(@pid int)
    RETURNS  INT
    AS
    BEGIN
    DECLARE @Return int
    SELECT @Return= CASE @pid
    -- SOME OTHER Comment
    WHEN 208 THEN  4
    WHEN 283 THEN  4
    WHEN 402 THEN  4
    WHEN 42 THEN  4

    --SOME OTHER Comment
    WHEN 211 THEN  3
    WHEN 286 THEN 3
    WHEN 399 THEN 3
    WHEN 45 THEN 3

    --SOME OTHER Comment
    WHEN 209 THEN 1
    WHEN 284 THEN 1
    WHEN 397 THEN 1
    WHEN 43 THEN 1

    --SOME Other Comment
    WHEN 210 THEN 2
    WHEN 285 THEN 2
    WHEN 398 THEN 2
    WHEN 44 THEN 2

    ELSE 0
    END
    RETURN @Return
    END

2 个答案:

答案 0 :(得分:5)

CASE       
    WHEN @pid in (208, 283, 402, 42)
        THEN  4      
    WHEN @pid in (211, 286, 399, 45)
        THEN  3      
    WHEN @pid in (209, 284, 397, 43)
        THEN  1        
    WHEN @pid in (210, 285, 398, 44)
        THEN  2      
    ELSE 0     
END 

答案 1 :(得分:2)

你不能用IN清理东西吗?

...
SELECT @Return= CASE 
WHEN @pid IN (208, 283, 402, 42) THEN  4
WHEN @pid IN (211, 286, 399, 45) THEN  3
...