我如何编写 WHERE cluase 以便它返回符合条件的行,如果没有这样的记录,它应该返回表中的所有记录?
6 回答
0
使用 UNION ALL:
select t.* from table t where condition
union all
select t.* from table t cross join (select count(*) cnt from table where condition) c
where c.cnt=0
或者(更有效):
select col1, col2, ... colN
from
(
select t.*, sum(case when condition then 1 else 0 end) over() cnt from table
) s
where condition or s.cnt=0
替换condition为您的 WHERE 条件
于 2021-05-31T08:09:17.440 回答
0
这让我很满意:
WHERE (
ISNULL(@variable, '') = ''
OR @variable = [Column]
)
不完全是我上面描述的,但如果条件不满足,它会返回所有记录。但是,在这种情况下,条件将为变量赋值。
于 2021-05-31T08:45:09.220 回答
0
第一种方法
Where ( ISNULL(@Param,'')='' OR ColumnName = @Param)
第二种方式
WHERE ( ColumnName =CASE WHEN @Param IS NULL THEN ColumnName
ELSE @Param
END)
第三种方式
WHERE (@Param ='' OR @Param =ColumnName)
于 2021-05-31T09:18:35.763 回答
0
我会推荐一个 CTE not exists:
with cte as (
select t.*
from t
where . . .
)
select *
from cte
union all
select *
from t
where not exists (select 1 from cte);
于 2021-05-31T12:09:10.853 回答
0
您可以考虑的一种方法t-sql是用于@@rowcount确定是否需要返回所有行。
这样做的好处是您可以获得两个单独的执行计划,其中一个仅针对您的第一个exists标准进行了优化,如果大多数结果都exists满足条件,这将是有益的。
select <columns>
from <table>
where <condition>
if @@rowcount=0
begin
select <columns>
from <table>
end
于 2021-05-31T08:20:46.073 回答
0
一种方法是:
SELECT *
FROM Person
WHERE
Name = 'John'
OR NOT EXISTS(SELECT null FROM Person WHERE Name = 'John')
由于评论中提到的所有这些充分理由,我不喜欢它。如果我将这个需求作为我正在创建的系统的一部分提交给我,我可能会检查对需求的需求;从表中选择所有行很少有用,如果它是您使用条件查询的那种表:“亲爱的用户,我们找不到您的名字叫 John 所以这里是系统中的其他 42.7 亿用户,分页大小为 100 "
于 2021-05-31T08:23:11.990 回答