4

SQL Server 2008 中是否有类似下面的方法?

可以根据条件指定外部应用(连接)表吗?

declare @bGetExtendedInfo bit
set @bGetExtendedInfo = 1

declare @param nvarchar(24)
set @param = 'CO-02-BBB'

select t1.*, t2.ID
from t1
outer apply (
              case when @bGetExtendedInfo= 0 
                  then (select 0) as ID  /* dummy value */
                  /*really expensive query trying to avoid when extended info is not needed*/
                  else (select top 1 ID from tbl1 where tbl1.code = @param)
              end
             ) t2
4

2 回答 2

4

您只需加入即可轻松完成此操作:

SELECT t1.*, t2.*
FROM   t1 cross join
       (SELECT *
        FROM (SELECT top 1 tb10.*, 0 as bCcond src FROM tb10 
              UNION ALL
              SELECT top 1 tb11.*, 1 as bCcond src FROM tb11
             ) t
        WHERE @bCond = bCcond
       ) t2

在表是非常复杂的连接的情况下,执行top之前的union all操作还应该有助于优化器生成更好的查询计划。

此外,top不使用 anorder by通常是不受欢迎的。它可以通过不同的调用返回不同的行,但不能保证这些行是随机的。

于 2013-02-04T14:17:56.907 回答
4

试试这个,

DECLARE @bCond BIT
SET @bCond = 1

SELECT t1.*, t2.*
FROM   t1 OUTER APPLY
             (
                SELECT TOP 1 *
                FROM
                    (
                        SELECT *, 'a' src FROM tb10
                        UNION ALL
                        SELECT *, 'b' src FROM tb11
                    )s
                WHERE   src = CASE WHEN @bCond = 0 THEN 'a' ELSE 'b' END
             ) t2
于 2013-02-04T13:34:23.477 回答