[英]SQL:where column not equal return result else result equals blank value
So I am coming across an issue with a sql query (mssql) I have been working on that has multi-statement where clause, and one of the where statements may or may not return a value. 所以我遇到了我一直在处理的SQL查询(mssql)问题,该查询具有多语句where子句,其中where语句之一可能返回也可能不返回值。 If the where condition is not met how can I have it return an empty value and still return the rest of my results?
如果不满足where条件,该如何返回一个空值并仍然返回其余结果? I am also using multiple CTEs.
我也在使用多个CTE。
Here is my select clause: 这是我的选择子句:
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
Here is my where clause: 这是我的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
I want to add something like this to my where clause: 我想在我的where子句中添加以下内容:
and cte_mismatch.MismatchSerialNumber != cte_devinfo.SerialNumber
but this condition may never occur, and if it doesn't how can I ignore the condition and just return ' ' so the rest of the query will run? 但是这种情况可能永远不会发生,如果不能解决,我该如何忽略这种情况而只返回'',以便其余查询继续运行?
First, rewrite your query using ANSI joins: 首先,使用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
I changed all joins except the first one to outer, to allow for missing records for slots, changers, and mismatches. 我将除第一个以外的所有联接更改为外部联接,以允许丢失插槽,更换器和不匹配记录。
dev_CTE
remains required, though, because all tables are joined to the record from it. 但是,仍然需要
dev_CTE
,因为所有表都已从中加入到记录中。
Now you can add a where
clause like this: 现在,您可以添加一个
where
子句,如下所示:
WHERE cte_mismatch.MismatchSerialNumber IS NULL OR cte_mismatch.MismatchSerialNumber != cte_devinfo.SerialNumber
This condition allows for NULL
in MismatchSerialNumber
, or even for missing cte_mismatch
record. 此条件允许
MismatchSerialNumber
为NULL
,甚至允许缺少cte_mismatch
记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.