Use a stored procedure parameter for unit parameter of DATE_SUB
I would like to know if it's possible to pass a parameter to a mysql stored procedure and use this parameter as the unit parameter of the DATE_SUB function. It seems that the unit parameter is a reserved word so I don't know if there's a type for unit.
Exemple of what I'm trying to do :
DELIMITER $$
DROP PROCEDURE IF EXISTS `test` $$
CREATE DEFINER=`root`@`%` PROCEDURE `test`(param1 unit)
BEGIN
select DATE_SUB(now(), INTERVAL 1 param1);
END $$
DELIMITER ;
UPDATE 1 I tried with a prepare statement, I'm able to create the stored proc.
DELIMITER $$
DROP PROCEDURE IF EXISTS `test` $$
CREATE DEFINER=`root`@`%` PROCEDURE `test`(param1 varchar(10))
BEGIN
PREPARE stmt FROM 'SELECT DATE_SUB(now(), INTERVAL 1 ?)';
EXECUTE s开发者_JAVA技巧tmt USING @param1;
END $$
DELIMITER ;
When I executed it : CALL test('WEEK'); You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?)' at line 1
What you are trying to do is not possible in a stored procedure, with or without a prepared statement.
You could do something similar like this:
DELIMITER $$
DROP PROCEDURE IF EXISTS test_proc $$
CREATE PROCEDURE test_proc(param1 varchar(20))
BEGIN
CASE UPPER(param1)
WHEN 'MICROSECOND' THEN select DATE_SUB(now(), INTERVAL 1 MICROSECOND);
WHEN 'SECOND' THEN select DATE_SUB(now(), INTERVAL 1 SECOND);
WHEN 'MINUTE' THEN select DATE_SUB(now(), INTERVAL 1 MINUTE);
WHEN 'HOUR' THEN select DATE_SUB(now(), INTERVAL 1 HOUR);
WHEN 'DAY' THEN select DATE_SUB(now(), INTERVAL 1 DAY);
WHEN 'WEEK' THEN select DATE_SUB(now(), INTERVAL 1 WEEK);
WHEN 'MONTH' THEN select DATE_SUB(now(), INTERVAL 1 MONTH);
WHEN 'QUARTER' THEN select DATE_SUB(now(), INTERVAL 1 QUARTER);
WHEN 'YEAR' THEN select DATE_SUB(now(), INTERVAL 1 YEAR);
ELSE select 'UNEXPECTED UNIT';
END CASE;
END $$
DELIMITER ;
精彩评论