如何在sql函数中使用字符串变量值作为参数

时间:2013-11-15 11:51:07

标签: mysql cursor

SELECT NRL_FREQUENCY_NO,NRL_FREQUENCY_TERM into frequency_no,frequency_term 
       from notification_rule 
       WHERE NRL_ID=nrl_id;

SELECT TIMESTAMPADD(frequency_term,frequency_no,nrl_fire_date) into nrl_next_fire_date;

假设frequency_term ='Month',则TIMESTAMPADD必须使用参数frequency_term作为月份

1 个答案:

答案 0 :(得分:1)

您需要使用预准备语句,例如 -

SET @frequency_term = 'DAY';
SET @frequency_no = 1;
SET @nrl_fire_date = '2013-11-15';

SET @query = CONCAT('SELECT TIMESTAMPADD(', @frequency_term, ', ', @frequency_no, ', ''', @nrl_fire_date, ''') INTO @nrl_next_fire_date');

PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SELECT @nrl_next_fire_date;

+---------------------+
| @nrl_next_fire_date |
+---------------------+
| 2013-11-16          |
+---------------------+