I want to create a stored procedure with multiple input optional parameters. If parameters for at least one of the fields are given, I still want some result meeting the criteria.
Here is my table definition:
CREATE TABLE `tblinquiries` (
`UID` varchar(50) DEFAULT NULL,
`ReviewDate` date NOT NULL,
`InquiryId` varchar(50) NOT NULL,
`AuditStatus` varchar(50) DEFAULT NULL,
`AssignedTo` varchar(50) DEFAULT NULL,
`Result` int(2) DEFAULT NULL,
`ResultCategories` int(2) DEFAULT NULL,
`AuditBy` varchar(50) DEFAULT NULL,
`Remarks` varchar(200) DEFAULT NULL,
`StartTime` datetime DEFAULT NULL,
`EndTime` datetime DEFAULT NULL,
PRIMARY KEY (InquiryId)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Here is a sample data set:
INSERT INTO `tblinquiries` (`UID`, `ReviewDate`, `InquiryId`, `AuditStatus`, `AssignedTo`, `Result`, `ResultCategories`, `AuditBy`, `Remarks`, `StartTime`, `EndTime`) VALUES
('user1', '2018-07-07', '109933881', 'Assigned', 'auditor1', NULL, NULL, NULL, NULL, '2018-07-15 08:03:47', NULL),
('user2', '2018-07-07', '109933885', 'Assigned', 'auditor2', NULL, NULL, NULL, NULL, '2018-07-15 08:04:13', NULL),
('user3', '2018-07-07', '109933909', 'Complete', 'auditor3', 1, auditor3, NULL, NULL, '2018-07-15 08:06:42', '2018-07-15 08:10:42'),
('user4', '2018-07-08', '109933916', 'Check', NULL, NULL, NULL, NULL, NULL, NULL, NULL),
('user5', '2018-07-08', '109933917', 'Check', NULL, NULL, NULL, NULL, NULL, NULL, NULL),
('user6', '2018-07-08', '8790804', 'Complete', 'auditor1', 1, NULL, 'auditor1', NULL, '2018-07-14 21:19:25', '2018-07-14 21:21:29');
Here is my stored procedure:
DROP procedure IF EXISTS `spInquiries`;
DELIMITER $$
CREATE PROCEDURE `spInquiries` (IN `pReviewStartDate` DATE, IN `pReviewEndDate` DATE, IN `pAuditStartDate` DATE, IN `pAuditEndDate` DATE)
BEGIN
SELECT * FROM tblinquiries
WHERE
(ReviewDate BETWEEN pReviewStartDate AND pReviewEndDate)
AND (DATE(EndTime) BETWEEN pAuditStartDate AND pAuditEndDate);
END$$
DELIMITER ;
After researching a lot, I found this stackoverflow question that has some similarity. But I don't how I can make 2 parameters (e.g - pAuditStartDate, pAuditEndDate) null for the WHERE clause.
I have added an SQL fiddle here.
I want some result for both the command:
CALL spInquiries('', '', '2018-07-01', '2018-07-31');
CALL spInquiries('2018-07-01', '2018-07-31', '', '');
How can I achieve that?