简体   繁体   English

在SQL Server where子句中使用if / case

[英]using if/case in sql server where clause

I'm trying to add a column in where clause in SQL Server 2005, but issue is I have to add it for a given condition like 我正在尝试在SQL Server 2005的where子句中添加一列,但问题是我必须为给定条件添加它,例如

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

but when I try this SQL Server gives me error: 但是当我尝试这个SQL Server给我错误:

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

I did some R&D and found that I should use case statement instead and then I tried this 我做了一些研发,发现我应该改用case语句,然后尝试

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

but now it's giving error: 但现在它给出了错误:

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

Can any one help me to sort out the problem? 谁能帮我解决问题? Thanks. 谢谢。

EDIT 编辑

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) 

I want to add this condition when spm David otherwise this condition should not be there. 我想在spm David时添加此条件,否则此条件不应存在。

You can remove the CASE statement and substitute AND (@Val<> 'test' OR (@Val = 'test' AND condition 3)) : 您可以删除CASE语句并替换为AND (@Val<> 'test' OR (@Val = 'test' AND condition 3))

WHERE <condition  1>
AND <condition 2>
AND (@Val<> 'test' OR (@Val = 'test' AND <condition 3>))
where condition  1
and condition 2
and ((@val='test' and condition 3) Or (@val!='test'))

Thanks for all to answer the question, but I used a little trick to solve the problem in this way 感谢所有回答此问题的人,但我使用了一些技巧来以这种方式解决问题

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 

means i used the same full query with condition, hope this trick will help someone to solve his issue. 表示我对条件使用了相同的完整查询,希望此技巧可以帮助某人解决他的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM