我想写一个这样的程序:
CREATE PROCEDURE `addByType`(IN myDate DATETIME, IN myType INT, OUT output DATETIME)
BEGIN
DECLARE unit ?;
CASE
WHEN myType = 1 THEN
SET unit = HOUR;
WHEN myType = 2 THEN
SET unit = DAY;
...
END CASE;
SELECT TIMESTAMPADD(unit, 1, myDate) INTO output;
END
有可能吗?我可以将unit关键字存储到变量中吗?还是有另一种方法可以实现同样的目标吗?
答案 0 :(得分:1)
请试试这个:
CREATE PROCEDURE `addByType`(IN myDate DATETIME, IN myType INT, OUT output DATETIME)
BEGIN
CASE
WHEN myType = 1 THEN
SET @unit = 'HOUR';
WHEN myType = 2 THEN
SET @unit = 'DAY';
END CASE;
SET @sql = CONCAT('SELECT TIMESTAMPADD(', @unit, ', 1, \'', myDate, '\') INTO @output;');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET output = @output;
END
可能包含语法错误,必须查找某些内容。但我相信你能搞清楚。现在要走了,明天再看看。