我在 SQL Server View 中有相当长的 SQL 选择。
但是,我想要一个条件,这样如果没有返回行,那么它会更改 where 子句。
查询概述如下:
SELECT COL1, COL2, COL3, COL4............(15 columns)
FROM TABLE1 inner join TABLE2 ON t1 = t2 (10 tables)
WHERE a = b
所以我想要的是,如果上面的查询返回 0 行,则返回结果:
SELECT COL1, COL2, COL3, COL4............(15 columns)
FROM TABLE1 inner join TABLE2 ON t1 = t2 (10 tables)
WHERE a = c
我如何在 View 中解决这个问题?
提前致谢
最佳答案
使用 common table expression与 not exists()
;with cte as (
/* big query here without where clause of `a = b` or `a = c` */
)
select *
from cte
where a = b
or ( a = c
and not exists (select 1 from cte where a = b)
)
示例:
create table t (value int);
insert t values (0),(1),(3),(4),(5);
with cte as (
select *
from t
)
select *
from cte
where value = 2
or ( value = 3
and not exists (select 1 from cte where value=2)
)
返回3
rextester 演示:http://rextester.com/NDC30620
关于sql - 如果第一次选择返回 0 计数,则返回备用 View 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42840050/