I am writing a stored procedure in MySQL with a dynamic query as shown below:
DROP PROCEDURE IF EXISTS test;
DELIMITER //
CREATE PROCEDURE test(
IN STATUS VARCHAR(20),
IN CREATED_ON1 VARCHAR(10)
)
BEGIN
SET @query="SELECT STATUS, COUNT(*) FROM CONTROL WHERE ID=ID";
IF STATUS IS NOT NULL THEN
SET @query=CONCAT(@query, " AND STATUS='",STATUS,"'");
END IF;
IF CREATED_ON1 IS NOT NULL THEN
SET @query=CONCAT(@query, " AND DATE_FORMAT(CREATED_ON,'%d-%m-%Y')>='",
CREATED_ON1, "'");
END IF;
SET @query=CONCAT(@query, " GROUP BY STATUS");
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
DELIMITER ;
I intend to rewrite this procedure with the signature shown below. This will provide the right logic in comparing the dates.
DROP PROCEDURE IF EXISTS test;
DELIMITER //
CREATE PROCEDURE test(
IN STATUS VARCHAR(20),
IN CREATED_ON1 DATE
)
The main question is; how do I concatenate the predicate with date to the @query?