这是SELECT:
SELECT DISTINCT PN.PART_NUMBER, PN.SHORT_CODE, DES.DESCRIPTION
FROM MAS_PART PN
LEFT JOIN CF_DESCRIPTION DES
ON PN.LOCAL_DESCRIPTION_ID = DES.DESCRIPTION_ID
WHERE PN.PART_CODE = 'M'
AND PN.PART_TYPE_ID = IN_PART_TYPE_ID
AND PN.PART_GROUP_ID = IN_PART_GROUP_ID
ORDER BY PN.PART_NUMBER;
这两个变量是 IN_PART_TYPE_ID 和 IN_PART_GROUP_ID 。有没有什么方法可以评估关于这两个变量的WHERE子句,只有当它们不是NULL时?或者唯一的方法是使用IF子句重复SELECT 3次并更改WHERE子句?
答案 0 :(得分:4)
OR operatior会有所帮助:
SELECT DISTINCT PN.PART_NUMBER, PN.SHORT_CODE, DES.DESCRIPTION
FROM MAS_PART PN
LEFT JOIN CF_DESCRIPTION DES
ON PN.LOCAL_DESCRIPTION_ID = DES.DESCRIPTION_ID
WHERE PN.PART_CODE = 'M'
AND (PN.PART_TYPE_ID = IN_PART_TYPE_ID or IN_PART_TYPE_ID is null)
AND (PN.PART_GROUP_ID = IN_PART_GROUP_ID or IN_PART_GROUP_ID is null)
ORDER BY PN.PART_NUMBER;
另一种选择是使用NVL:
SELECT DISTINCT PN.PART_NUMBER, PN.SHORT_CODE, DES.DESCRIPTION
FROM MAS_PART PN
LEFT JOIN CF_DESCRIPTION DES
ON PN.LOCAL_DESCRIPTION_ID = DES.DESCRIPTION_ID
WHERE PN.PART_CODE = 'M'
AND PN.PART_TYPE_ID = NVL(IN_PART_TYPE_ID, PN.PART_TYPE_ID)
AND PN.PART_GROUP_ID = NVL(IN_PART_GROUP_ID, PN.PART_GROUP_ID)
ORDER BY PN.PART_NUMBER;
但只有当PN.PART_TYPE_ID和PN.PART_GROUP_ID不为空时它才会起作用