MySQL在存储过程中准备的语句表现不尽如人意

时间:2016-06-23 17:20:04

标签: mysql stored-procedures prepared-statement

我有这个MySQL存储过程

DELIMITER $$

CREATE DEFINER=`dbuser`@`%` PROCEDURE `getTranslatedAnswer`(IN questionDesc VARCHAR(2500), col VARCHAR(10))
BEGIN
    SET @paramVal = questionDesc;
    SET @str = CONCAT('SELECT C.',col,' AS `answer`, D.',col,' AS `message` 
        FROM `option_group` A 
            INNER JOIN `questions_answers` B ON A.`option_id` = B.`option_id` 
            INNER JOIN `answers` C ON B.`answers_id` = C.`answers_id` 
            INNER JOIN  `chat_message` D ON A.`option_group_id` = D.`option_group_id` 
        WHERE UPPER(`A`.',col,') = ? LIMIT 1');
    PREPARE stmt FROM @str;
    EXECUTE stmt USING @paramVal;
    DEALLOCATE PREPARE stmt;
END

使用

调用上面的代码
call getTranslatedAnswer('我可以在机场买到预付SIM卡吗?','zh_chs');

将返回0行。与我在下面调用裸SQL时相比

SELECT C.zh_chs AS `answer`, D.zh_chs AS `message` 
        FROM `option_group` A 
            INNER JOIN `questions_answers` B ON A.`option_id` = B.`option_id` 
            INNER JOIN `answers` C ON B.`answers_id` = C.`answers_id` 
            INNER JOIN  `chat_message` D ON A.`option_group_id` = D.`option_group_id` 
        WHERE UPPER(`A`.`zh_chs`) = '我可以在机场买到预付SIM卡吗?' LIMIT 1;

它返回1行。我在这里错过了什么吗?我该如何调试?请指教,谢谢!

1 个答案:

答案 0 :(得分:0)

我可能记得错了,但我似乎记得execute实际上没有像你期望的那样返回结果。 如果你尝试这样的话会怎么样?

DELIMITER $$

CREATE DEFINER=`dbuser`@`%` PROCEDURE `getTranslatedAnswer`(IN questionDesc VARCHAR(2500), col VARCHAR(10))
BEGIN
    SET @paramVal = questionDesc;
    DROP TEMPORARY TABLE IF EXISTS `t_getTranslatedAnswer`;
    SET @str = CONCAT('
        CREATE TEMPORARY TABLE `t_getTranslatedAnswer`
        SELECT C.',col,' AS `answer`, D.',col,' AS `message` 
        FROM `option_group` A 
            INNER JOIN `questions_answers` B ON A.`option_id` = B.`option_id` 
            INNER JOIN `answers` C ON B.`answers_id` = C.`answers_id` 
            INNER JOIN  `chat_message` D ON A.`option_group_id` = D.`option_group_id` 
        WHERE UPPER(`A`.',col,') = ? LIMIT 1');
    PREPARE stmt FROM @str;
    EXECUTE stmt USING @paramVal;
    DEALLOCATE PREPARE stmt;

    SELECT * FROM `t_getTranslatedAnswer`;
    DROP TEMPORARY TABLE `t_getTranslatedAnswer`;
END