문제

I would like to write a procedure like this:

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

Is it possible somehow? Can I store unit keyword into variable? Or is there another way to achieve the same?

도움이 되었습니까?

해결책

Please have a try with this one:

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

May include syntax errors, would have to look up certain things. But I'm sure you can figure it out. Gotta go now, will have a look again tomorrow.

P.S: Here's the manual entry for prepared statements.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top