在具有多个输入参数的条件下组合

时间:2013-04-08 06:53:04

标签: sql sql-server tsql

功能有一些参数,如
@a int, @b int, @c int , @d int

它只需要允许,值不为空 或 @a,@ b,@ c,@ d和@a + @b

的组合

我试过了,但它允许其他组合也像@a + @c

if((@a is not null) or (@b is not null) or (@c is not null) or (@d is not null) or ((@a is not null) and (@b is not null)))

有人能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

这个怎么样:

IF
    (
        @a IS NOT NULL 
        AND 
        @c IS NULL
        AND 
        @d IS NULL
    )
    OR
    (
        @b IS NOT NULL
        AND 
        @c IS NULL
        AND 
        @d IS NULL
    )
    OR 
    (
        @c IS NOT NULL
        AND 
        @a IS NULL
        AND 
        @b IS NULL
        AND 
        @d IS NULL
    )
    OR 
    (
        @d IS NOT NULL
        AND 
        @a IS NULL
        AND 
        @b IS NULL
        AND 
        @c IS NULL
    )

或者这个:

DECLARE @validate INT;
SELECT @validate = SUM(validate) 
FROM 
    ( 
        SELECT CASE WHEN @a IS NULL THEN 0 ELSE 1 END validate
        UNION
        SELECT CASE WHEN @b IS NULL THEN 0 ELSE 1 END 
        UNION
        SELECT CASE WHEN @c IS NULL THEN 0 ELSE 2 END 
        UNION
        SELECT CASE WHEN @d IS NULL THEN 0 ELSE 2 END 
    ) n;

IF @validate BETWEEN 1 AND 2