MySQL Procedure参数问题

时间:2014-08-16 08:23:48

标签: mysql stored-procedures

这是我的程序。

DELIMITER $$

DROP PROCEDURE IF EXISTS `wddb`.`DailyCollectionByCenter` $$
CREATE PROCEDURE `DailyCollectionByCenter`(IN fromDate VARCHAR(255), IN toDate VARCHAR(255))
BEGIN
  set @sql:=null;
  select group_concat(distinct concat('sum(if(c.center_name="',center_name,'",w.final_kg,0)) `', center_name,'`')order by center_id)
  from wd_collection_center
  into @sql;

  set @sql:=concat('SELECT w.purchase_date,', @sql, '
                  FROM wd_leaf_purchase w
                  join wd_leaves_supplier s on w.supplier_id = s.supplier_id
                  join wd_collection_center c on s.center_id = c.center_id
                  WHERE (w.purchase_date BETWEEN fromDate AND toDate)
                  group by w.purchase_date;');

  prepare st from @sql;
  execute st;
  deallocate prepare st;
END $$

DELIMITER ;

我已按上述程序调用上述程序。

CALL DailyCollectionByCenter("2010-01-10","2014-12-05")

但我收到错误Unknown column 'fromDate' in 'where clause'

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

你必须连接那些变量,它们不会被插值:

set @sql:=concat('SELECT w.purchase_date,', @sql, '
              FROM wd_leaf_purchase w
              join wd_leaves_supplier s on w.supplier_id = s.supplier_id
              join wd_collection_center c on s.center_id = c.center_id
              WHERE (w.purchase_date BETWEEN ''',
              fromDate,
              ''' AND ''',
              toDate,
              ''')
              group by w.purchase_date;');

因为结果是一个字符串,你必须将这些值放在单引号中。 由单引号括起的字符串中的两个单引号''将获得一个引号。否则你也可以使用\'