【问题标题】:using if/case in sql server where clause在 sql server where 子句中使用 if/case
【发布时间】:2014-05-13 13:54:45
【问题描述】:

我正在尝试在 SQL Server 2005 的 where 子句中添加一列,但问题是我必须为给定条件添加它,例如

where condition  1
and condition 2
if(@val !=null and @val = 'test')
begin
and condition 3
end

但是当我尝试这个 SQL Server 时,我会报错:

Incorrect syntax near the keyword 'and'. Severity 15 Procedure Name
Incorrect syntax near 'END'. Severity 15 Procedure Name

我做了一些研发,发现我应该改用case语句,然后我尝试了这个

where condition  1
    and condition 2
    CASE @val 
    WHEN 'test' THEN AND condition 3
END 

但现在它给出了错误:

Incorrect syntax near the keyword 'CASE'. Severity 15 Procedure Name

谁能帮我解决这个问题?谢谢。

编辑

select *
from Tables with joins
where ac_jd_date_closed >= convert(VARCHAR(10),dateadd(dd, -@period, getdate()), 101)
and ac_jd_date_closed <= convert(VARCHAR(10),dateadd(dd, 0, getdate()), 101) 
and lo_pc_last_name not in ('Shroder')
and lm_ap_pr_id NOT IN (4743, 2683) 

我想在 spm David 时添加这个条件,否则这个条件不应该存在。

【问题讨论】:

标签: sql sql-server


【解决方案1】:

您可以删除CASE 语句并替换为AND (@Val&lt;&gt; 'test' OR (@Val = 'test' AND condition 3))

WHERE <condition  1>
AND <condition 2>
AND (@Val<> 'test' OR (@Val = 'test' AND <condition 3>))

【讨论】:

  • 请注意,我已更新此内容,因为您需要将整个 AND 语句括在括号中。
【解决方案2】:
where condition  1
and condition 2
and ((@val='test' and condition 3) Or (@val!='test'))

【讨论】:

  • @roryap 你也可以使用!=(在sql server,我不知道其他db)
  • @roryap: 是的!=&lt;&gt; 是一样的
  • 只是检查。不知道。
  • @roryap 我只想向你们中的任何人澄清一件事,即在我的情况下,条件 3 不能作为语句起作用,因为它是有条件的。如果两个答案都符合我的要求,请告诉我。
  • 你为什么不发布条件3是什么
【解决方案3】:

感谢大家回答问题,不过我用了一个小技巧就这样解决了问题

if(@spm='David')
begin

select *
    from Tables with joins
    where ac_jd_date_closed >= convert(VARCHAR(10),dateadd(dd, -@period, getdate()), 101)
    and ac_jd_date_closed <= convert(VARCHAR(10),dateadd(dd, 0, getdate()), 101) 
    and lo_pc_last_name not in ('Shroder')
    and lm_ap_pr_id NOT IN (4743, 2683) 
end  
else 
begin 
select *
    from Tables with joins
    where ac_jd_date_closed >= convert(VARCHAR(10),dateadd(dd, -@period, getdate()), 101)
    and ac_jd_date_closed <= convert(VARCHAR(10),dateadd(dd, 0, getdate()), 101) 
    and lo_pc_last_name not in ('Shroder')
end 

表示我使用了相同的完整查询条件,希望这个技巧能帮助某人解决他的问题。

【讨论】:

    猜你喜欢
    • 2014-11-20
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    相关资源
    最近更新 更多