在函数内的多个AND / OR T-SQL语句中选择第一个或出现的记录

时间:2013-10-09 15:09:44

标签: sql sql-server tsql

我有以下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语句,所有这些都在一个函数中。

2 个答案:

答案 0 :(得分:0)

您可以将案例表达式用作:

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
                          );

答案 1 :(得分: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