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. If the where condition is not met how can I have it return an empty value and still return the rest of my results? I am also using multiple CTEs.
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 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:
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:
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.
Now you can add a where
clause like this:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.