简体   繁体   English

SQL条件条件,如果条件不满足,则返回所有

[英]SQL conditional where, return all if condition not met

I have a similar question to SQL Conditional Where and Conditional WHERE clause in SQL Server , except when the condition is not met, I want to return all rows (as if there were no WHERE clause). 我有一个与SQL Server中的 SQL Conditional WhereConditional WHERE子句类似的问题,除了不满足该条件时,我想返回所有行(就像没有WHERE子句一样)。

One solution could be to do the following. 一种解决方案是执行以下操作。 Note that <ColLetter> and <ColValue> are string insertions, where <ColLetter> will be one of ColA , ColB , ColC , or NULL , and <ColValue> will be a value that can appear in one of those columns (or is NULL if the <ColLetter> is). 请注意, <ColLetter><ColValue>是字符串插入,其中<ColLetter>将是ColAColBColCNULL ,而<ColValue>将是可以出现在那些列之一(或为NULL (如果<ColLetter>是)。

SELECT ID, ColA, ColB, ColC
FROM MainTable t
WHERE (
  -- <ColLetter> is not null, corresponding to a column name in MainTable
  (ISNULL(<ColLetter>, 0) <> 0 AND t.<ColLetter> =  <ColValue>)
  OR
  -- <ColLetter> is null, I want to return all rows
  (ISNULL(<ColLetter>, 0) = 0 AND t.ID is not null)
  )

The issue with this is that it checks the ID column for nulls unnecessarily (there won't be any nulls) and it is a large table. 这样做的问题是它不必要地检查ID列是否为空(不会有任何空值),并且它是一个大表。 Is there a better way to do this? 有一个更好的方法吗?

where case <colLetter>
     when '<nameOfColA>' then nameOfColA
     when '<nameOfColB>' then nameOfColB
     When '<nameOfColC>' then nameOfColC
     else isNull(<colValue>, 0) end 
      = isNull(<colValue>, 0)        

This boils down to 归结为

SELECT ID, ColA, ColB, ColC
FROM MainTable t
WHERE (
   -- <ColLetter> is null, I want to return all rows
   ISNULL(<ColLetter>, 0) = 0 
   -- Check the value otherwise
   OR t.<ColLetter> = <ColValue>)
  )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM