SQL Server - 什么是正确的语法?

问题描述:

我要写正确的语法吗?SQL Server - 什么是正确的语法?

伪代码

select * from products 
if @value is not null begin where category = @value end 
+ if @value1 is not null begin where other1 = @value1 end 
+ if @value2 is not null begin where other2 = @value2 end 
+ if @value3 is not null begin where other3 = @value3 end 

我是小白。我不想写一个动态查询。如何编写上述查询?

+1

这是一个错误? “ifs”中的“@ value”应该是“@ value1”,“@ value2”等吗? – Mureinik

这里是你如何做到这一点,而无需使用动态SQL

select * 
from products 
where (@value is null or category = @value) 
     and (@value1 is null or other1 = @value1) 
     and (@value2 is null or other2 = @value2) 
     and (@value3 is null or other3 = @value3) 

它是如何工作的?

取这条线@value is null or category = @value

上面的条件检查@value是否为null。如果是,则整条线/条件评估为true。所以我们忽略了那里或其中的一部分。

同样适用于所有其他条件。

希望这个清楚!