【问题标题】:SQL Server - What is the correct syntax?SQL Server - 什么是正确的语法?
【发布时间】:2017-10-28 04:52:55
【问题描述】:

我写的语法正确吗?

伪代码

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

我是菜鸟。我不想写动态查询。上面的查询怎么写?

【问题讨论】:

  • 这是错字吗? ifs 中的 @value 是否应该是 @value1@value2 等?

标签: sql if-statement syntax where


【解决方案1】:

这是不使用动态 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 是否为空。如果是,则整行/条件评估为真。所以我们忽略了那里的 or 部分。

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

希望这说明清楚!

【讨论】:

    猜你喜欢
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多