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
答案 0 :(得分: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
答案 1 :(得分: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
的情况下执行order by
通常不赞成。它可以返回具有不同调用的不同行,但不保证行是随机的。