SQL:其中列不等于返回结果,否则结果等于空值

时间:2014-09-10 17:13:59

标签: sql sql-server conditional where-clause

所以我遇到了一个sql查询(mssql)的问题我一直在研究多语句where子句,其中一个where语句可能会返回一个值,也可能不会返回一个值。如果不满足where条件,我怎么能让它返回一个空值并仍然返回我的其余结果?我也在使用多个CTE。

这是我的select子句:

select cte_devinfo.SerialNumber,
    cte_devinfo.DeviceName,
    cte_devinfo.DeviceID, 
    dev_CTE.concurrencies,
    (cte_slots.LocationIndex +1) as 'Total Media',
    cte_changer.SlotCount, cte_changer.TotalMountErrors, cte_changer.TotalMounts,
    cte_mismatch.MismatchSerialNumber
from cte_devinfo, dev_CTE, cte_slots, cte_changer, cte_mismatch

这是我的where子句:

where cte_devinfo.DeviceID = dev_CTE.DeviceParentID 
and cte_slots.LocationID = dev_CTE.DeviceParentID
and cte_changer.ChangerID = dev_CTE.DeviceParentID
and cte_mismatch.LocationID = dev_CTE.DeviceParentID 

我想在where子句中添加类似的内容:

and cte_mismatch.MismatchSerialNumber != cte_devinfo.SerialNumber 

但是这种情况可能永远不会发生,如果不是,我怎么能忽略这个条件而只返回''所以查询的其余部分会运行?

1 个答案:

答案 0 :(得分:2)

首先,使用ANSI连接重写您的查询:

select cte_devinfo.SerialNumber,
    cte_devinfo.DeviceName,
    cte_devinfo.DeviceID, 
    dev_CTE.concurrencies,
    (cte_slots.LocationIndex +1) as 'Total Media',
    cte_changer.SlotCount, cte_changer.TotalMountErrors, cte_changer.TotalMounts,
    cte_mismatch.MismatchSerialNumber
from cte_devinfo
inner join dev_CTE on cte_devinfo.DeviceID = dev_CTE.DeviceParentID
left outer join cte_slots on cte_slots.LocationID = dev_CTE.DeviceParentID
left outer join cte_changer on cte_changer.ChangerID = dev_CTE.DeviceParentID
left outer join cte_mismatch on cte_mismatch.LocationID = dev_CTE.DeviceParentID 

我将除第一个之外的所有连接更改为外部,以允许缺少插槽,转换器和不匹配的记录。但是,dev_CTE仍然是必需的,因为所有表都从它连接到记录。

现在您可以像这样添加where子句:

WHERE cte_mismatch.MismatchSerialNumber IS NULL OR cte_mismatch.MismatchSerialNumber != cte_devinfo.SerialNumber

此条件允许在NULLMismatchSerialNumber,或者甚至在cte_mismatch个记录丢失。