我写的语法正确吗?
伪代码
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
我是菜鸟。我不想编写动态查询。上面的查询怎么写?
这是不使用动态 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 是否为空。如果是,则整行/条件评估为真。所以我们忽略了那里的或部分。
这同样适用于所有其他条件。
希望这能说清楚!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句