我试图在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
我做了一些R& D,发现我应该使用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中添加这个条件,否则这个条件不应该存在。
答案 0 :(得分: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>))
答案 1 :(得分:2)
where condition 1
and condition 2
and ((@val='test' and condition 3) Or (@val!='test'))
答案 2 :(得分:0)
感谢所有人回答这个问题,但我用一个小技巧以这种方式解决问题
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
意味着我使用了相同的完整查询条件,希望这个技巧可以帮助某人解决他的问题。