sql-server - SQL Variable that means the same as *
问题描述
I'm trying to build a query that searches based on a series of different criteria, however sometimes you will only have to use some of the criteria.
I'd like to be able to do something like below where, to change the query I would only need to change the bits in bold at the top of the query, so as only to search by criteria1 and criteria2 without having to change any of the rest of the query. Thanks
Declare @criteria1 as varchar(1),@criteria2 as varchar(1),@criteria3 as varchar(1)
Set @criteria1 = 'a'
Set @criteria2 = 'b'
Set criteria3 = '*'
/*I don't want to change anything below this point*/
Select * from table where
a = @criteria1
b = @criteria2
c = @criteria3
解决方案
You can use conditional logic. If you want to use *
, then:
Select *
from table
where (a = @criteria1 or @criteria1 = '*') and
(b = @criteria2 or @criteria2 = '*') and
(c = @criteria3 or @criteria3 = '*');
More typically, NULL
would be used for this purpose -- because it works for any type and is not confused with any other "real" value:
Select *
from table
where (a = @criteria1 or @criteria1 is null) and
(b = @criteria2 or @criteria2 is null) and
(c = @criteria3 or @criteria3 is null);
Finally, SQL Server is going to do a full table scan in general with such conditions (the mixing of and
and or
). You might want to construct the query dynamically if you want the query to use indexes. However, if you are using one-character columns, then the indexes would not be particularly selective, so that might not apply in this particular case.
推荐阅读
- reactjs - JWT LocalStorage 与 Cookie
- python - 如何在 Numpy getfromtxt 中指定 uint8 的数据类型?
- c# - 如何让变量 totalCredit 正确递增
- python - python random.shuffle如何改变变量
- rust - 如何确定编译后的 Rust 二进制文件为什么需要特定符号?
- python - 如何从 int 变量设置 str 列表的长度
- python-3.x - 如何在 Databricks 中读取批量 excel 文件数据并加载到 spark 数据框中
- python - 如何在 matplotlib.pyplot 中设置 X 和 Y 轴标题
- python - Python:如何确定我正在运行程序的计算机是否使用欧洲小数
- amazon-web-services - AWS EC2 置放群组:分区与传播