具有动态表名的Mysql SP调用返回null作为结果

时间:2014-07-24 07:12:35

标签: mysql sql stored-procedures

我有以下SP,它在调用时返回null,但值在数据库中

CREATE PROCEDURE calculate_amount_sum(IN accid INT UNSIGNED, IN tableName VARCHAR(100), IN tablecode VARCHAR(100), OUT calc FLOAT)
READS SQL DATA
BEGIN
SET @GetSql = CONCAT('SELECT SUM(amount) INTO @total FROM ', tableName, ' WHERE code=', ''' , tablecode, ''' , ' AND account_id=', accid);
PREPARE stmt FROM @GetSql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET calc = @total; 
CREATE TEMPORARY TABLE IF NOT EXISTS tempT (`amount` float(10,4) NOT NULL)  ;
INSERT INTO cache values (calc) ;    
INSERT INTO cache values (@total) ;    
END //

错误是

Column 'amount' cannot be null

将值插入tempT表时

可能是什么原因,Thanx提前

2 个答案:

答案 0 :(得分:0)

替换您的代码如下:

SELECT SUM(IFNULL(amount,0)) INTO @total FROM

答案 1 :(得分:0)

最后我改变了这个,然后修好了

 SET @GetSql = CONCAT("SELECT SUM(amount) INTO @total FROM ", tableName, " WHERE code='", tablecode,"' AND account_id=", accid);  

谢谢