查询:如果列为空,则添加条件

时间:2014-05-21 08:37:51

标签: sql sql-server sql-server-2012 query-optimization

我正在使用存储过程处理此查询。简化术语的数据结构如下所示:包含表格的表格:

  • Elec_Nominations
  • Elec_Vacancy
  • 沃德
  • 扇区

为病房内的某个部门设置了多个空置座位。被提名为席位的个人将被输入Person数据库并链接到Elec_Nominations。此提名与WardElec_Vacancy相关联。提名也与部门(ELEC_SPEAKER_SECTOR)到Elec_Vacancy以及一些其他链接表相关联:

Sector Seats

我正在处理的查询

SELECT DISTINCT
    p.PERSON_ID,
    p.ID_NUMBER,
    CONCAT(p.FULLNAMES, (CONCAT((' ' COLLATE Latin1_General_CI_AS), p.SURNAME))) AS NAME,
    o.ORG_NAME,
    eiw.INTEREST_WARD_ID,
    scw.SUBCOUNCIL_ID,
    w.WARD_ID,
    ess.SPEAKER_SECTOR_ID,
    (SELECT TOP 1
     essg.NO_OF_SEATS
     FROM
         ELEC_SPEAKER_SECTOR_GROUP essg
         INNER JOIN ELEC_VACANCY ev ON essg.VACANCY_ID = ev.VACANCY_ID
     WHERE
         ev.VACANCY_ID = en.VACANCY_ID
     ORDER BY
         essg.ELEC_SECTOR_GROUP_SECTORS_ID DESC) AS SECTORSEATS,
    en.SECTOR_TEXT AS SECTORTEXT
    --essg.NO_OF_SEATS AS [SECTORSEATS]
FROM
    PERSON p
RIGHT OUTER JOIN 
    ELEC_NOMINATIONS en ON p.PERSON_ID = en.PERSON_ID
RIGHT OUTER JOIN 
    ELEC_INTEREST_WARD eiw ON en.INTEREST_WARD_ID = eiw.INTEREST_WARD_ID
LEFT JOIN 
    ELEC_INTEREST_GROUP eig ON eiw.INTEREST_GROUP_ID = eig.INTEREST_GROUP_ID
LEFT JOIN 
    ORGANISATION o ON eig.ORG_ID = o.ORG_ID
LEFT JOIN 
    WARD w ON eiw.WARD_ID = w.WARD_ID
LEFT JOIN 
    ELEC_SPEAKER_SECTOR ess ON eiw.SPEAKER_SECTOR_ID = ess.SPEAKER_SECTOR_ID
LEFT JOIN 
    SUBCOUNCILWARD scw ON w.WARD_ID = scw.WARD_ID
    --INNER JOIN ELEC_VACANCY ev ON en.VACANCY_ID = ev.VACANCY_ID
    --INNER JOIN ELEC_SPEAKER_SECTOR_GROUP essg ON ev.VACANCY_ID = essg.VACANCY_ID
WHERE
    ess.SPEAKER_SECTOR_ID IN (SELECT s.item FROM ufn_SplitIntArray(@P_Sectors, ',') s)
    AND w.WARD_ID IN (SELECT s.item FROM ufn_SplitIntArray(@P_Wards, ',') s)
    AND o.ORG_ID = @P_Org_ID
    --AND en.ELECTED = 1
ORDER BY
    w.WARD_ID

此查询的输出将进入此GridView

Sector Seats Gv

好的,我仍然需要从客户那里了解如何确定行业席位。问题在于,如果我说en.Elected = 1,它只显示被选举的人,但它没有显示甚至没有空缺的部门和病房(即第3和第5)行不会显示。)

当我打字时,我想到了什么。我会尝试研究以确定我是否可以这样做:

AND EVAL(ISNULL(en.NOMINATION_ID, 1))

或SQL中的某些内容:

if(en.NOMINATION_ID == null)
    true
else
    en.Elected == true

1 个答案:

答案 0 :(得分:1)

用例子句:

and columnfilter = case when columnempty is null then (condition) else columnfilter

另外,请参阅这些回答:
SQL Server 2012 - Case statement in where clause
"CASE" statement within "WHERE" clause in SQL Server 2008