0

我有以下 SQL(示例):

SET @Return_Value = = (SELECT Top 1
                          (CASE WHEN .... THEN ColumValue1 ELSE ColumValue2 END)
                        FROM TableA WHERE (Lots of AND Statements)
                         AND
                          (
                            (bla1)
                            OR
                            (bla2)
                            OR
                            (bla3)
                        )

bla1 等是从 TableA 中检索列值的逻辑。如果在没有执行 bla2 或 bla3 的情况下发现它们,我如何从 bla1 返回值,因为它们可能会覆盖我正在寻找的内容?换句话说,如果前一个没有找到数据,我只想执行 OR 语句,所有这些都在一个函数中。

4

2 回答 2

0

你可以使用order by,比如

select Top 1
    CASE WHEN .... THEN ColumValue1 ELSE ColumValue2 END
FROM TableA
WHERE
   (Lots of AND Statements) AND
   (
        (bla1) OR
        (bla2) OR
        (bla3)
   )
order by
   case
       when (bla1) then 1
       when (bla2) then 2
       when (bla3) then 3
       else 999
   end

或者您可以尝试简化它(但您必须检查性能):

select Top 1
    CASE WHEN .... THEN ColumValue1 ELSE ColumValue2 END
FROM TableA
    outer apply (
        select
            case
                when (bla1) then 1
                when (bla2) then 2
                when (bla3) then 3
            end as T
    ) as C
WHERE
   (Lots of AND Statements) and
   C.T is not null
order by C.T

或者,例如,您可以使用union类似这样的东西:

with cte as (
    select Top 1
        CASE WHEN .... THEN ColumValue1 ELSE ColumValue2 END as data
    FROM TableA
    WHERE
        (Lots of AND Statements)
), cte2 as (
    select top 1 data, 1 as c from cte where (bla1)
    union all
    select top 1 data, 2 as c from cte where (bla2)
    union all
    select top 1 data, 3 as c from cte where (bla3)
)
select top 1 data
from cte2
order by c
于 2013-10-09T17:42:33.867 回答
0

您可以将 case 表达式用作:

SET @Return_Value = (SELECT Top 1
                          (CASE WHEN .... THEN ColumValue1 ELSE ColumValue2 END)
                        FROM TableA WHERE (Lots of AND Statements)
                         AND
                          ( 1 = case when condition1 then 1
                                case when condition2 then 1
                                case when condition3 then 1
                                end
                          );
于 2013-10-09T16:13:33.843 回答