SQL WHERE ... IN子句,可能为null参数

时间:2013-05-01 18:18:05

标签: sql where-clause conditional-statements

我的WHERE子句遇到了一些问题(使用SQL 2008)。我必须创建一个存储过程,该过程根据7个参数返回结果列表,其中一些参数可能为null。有问题的是@elements,@ category和@edu_id。它们可以是id列表,也可以为null。如果参数不为null,您可以在我的where子句中看到我的特定代码可以工作。如果它们为null,我不确定如何编写sql代码。这些字段在数据库中是INT。

我希望我的问题足够明确。以下是我的查询。

BEGIN
DECLARE @elements nvarchar(30)
DECLARE @jobtype_id INT
DECLARE @edu_id nvarchar(30)
DECLARE @categories nvarchar(30)
DECLARE @full_part bit
DECLARE @in_demand bit
DECLARE @lang char(2)

SET @jobtype_id = null
SET @lang = 'en'
SET @full_part = null -- full = 1, part = 0
SET @elements = '1,2,3'
SET @categories = '1,2,3'
SET @edu_id = '3,4,5'

select 
jobs.name_en,
parttime.fulltime_only,
jc.cat_id category,
je.element_id elem,
jt.name_en jobtype,
jobs.edu_id minEdu,
education.name_en edu
from jobs
left join job_categories jc
on (jobs.job_id = jc.job_id)
left join job_elements je
on (jobs.job_id = je.job_id)
left join job_type jt
on (jobs.jobtype_id = jt.jobtype_id)
left join education
on (jobs.edu_id = education.edu_id)
left join 
(select job_id, case when (jobs.parttime_en IS NULL OR jobs.parttime_en = '') then 1 else 0 end fulltime_only from jobs) as parttime
on jobs.job_id = parttime.job_id
where [disabled] = 0    
and jobs.jobtype_id = isnull(@jobtype_id,jobs.jobtype_id)
and fulltime_only = isnull(@full_part,fulltime_only)
-- each of the following clauses should be validated to see if the parameter is null
-- if it is, the clause should not be used, or the SELECT * FROM ListToInt... should be replaced by 
-- the field evaluated: ie if @elements is null, je.element_id in (je.element_id)
and je.element_id IN (SELECT * FROM ListToInt(@elements,','))
and jc.cat_id IN (SELECT * FROM ListToInt(@categories,','))
and education.edu_id IN (SELECT * FROM ListToInt(@edu_id,','))

order by case when @lang='fr' then jobs.name_fr else jobs.name_en end;  

END

3 个答案:

答案 0 :(得分:2)

这样的东西
and (@elements IS NULL OR je.element_id IN 
(SELECT * FROM ListToInt(@elements,',')))
and (@categories IS NULL OR 
jc.cat_id IN (SELECT * FROM ListToInt(@categories,',')))
....

应该做的伎俩

答案 1 :(得分:0)

je.element_id IN (SELECT * FROM ListToInt(@elements,',')) OR @elements IS NULL

每个人的方式

答案 2 :(得分:0)

您是否尝试过显式比较NULL?

and (@elements is null or je.element_id IN (SELECT * FROM ListToInt(@elements,','))

等等。