我正在努力准备好陈述

时间:2016-02-11 18:41:48

标签: mysql prepared-statement mariadb concat

...表名是参数。我在这里找到了解决方案:unable to store return value from execute statement in mysql 但这对我不起作用。这是我的测试:

SET @v_sourceTableSize = 0;
SET @parameter_sourceTable = category;
SET @v_query = CONCAT("SELECT COUNT(*) INTO ",@v_sourceTableSize," FROM ",@parameter_sourceTable);

category是我的数据库中的一个表。当我运行它时,没有任何反应。没有错误,没有。有没有办法让它发挥作用?我从早上起就一直在寻找解决方案!


修改
我在引号之间放置了“类别”,现在它正在工作,但是我的原始程序却没有。请看一下:

DROP PROCEDURE IF EXISTS insert_categories;
DELIMITER $$
CREATE PROCEDURE insert_categories(
    IN parameter_sourceTableIdColumnName INTEGER,
    IN parameter_sourceTable VARCHAR(25),
    IN parameter_sourceColumn VARCHAR(25),
    IN parameter_destinationParentCategoryID INTEGER)

    MODIFIES SQL DATA

    BEGIN
        DECLARE v_parameterSourceTable VARCHAR(25) DEFAULT "";
        DECLARE v_sourceTableSize INTEGER;
        DECLARE v_counter INTEGER DEFAULT 0;
        DECLARE v_query VARCHAR(100) DEFAULT "";
        DECLARE v_recordName VARCHAR(25) DEFAULT "";
        SET v_parameterSourceTable = parameter_sourceTable;
        SET v_query = CONCAT("SELECT COUNT(*) INTO ",v_sourceTableSize," FROM ",v_parameterSourceTable);
        PREPARE stmt FROM v_query;
        EXECUTE stmt;
        SELECT v_sourceTableSize;
        #SET v_sourceTableSize := (SELECT COUNT(*) FROM parameter_sourceTable);
        SET v_sourceTableSize = v_sourceTableSize + 1;
        WHILE v_counter < v_sourceTableSize DO
            SET v_counter = v_counter + 1;
            SET v_recordName = (SELECT parameter_sourceColumn 
                                FROM v_parameterSourceTable 
                                WHERE parameter_sourceTableIdColumnName = v_counter);
            CALL insertCategory(v_recordName, parameter_destinationParentCategoryID);
        END WHILE;
    END $$    
DELIMITER ;

我收到了这个错误:

1064 - 您的SQL语法出错;检查与MariaDB服务器版本对应的手册,以便在'v_query附近使用正确的语法;         执行stmt;         SELECT v_sourceTableSize;                 在第17行设置v_sourceTa'

1 个答案:

答案 0 :(得分:0)

  

预准备语句可以访问用户定义的变量,但不能访问本地变量   变量或程序的参数。

    SET @v_query = CONCAT("SELECT COUNT(*) INTO ",v_sourceTableSize," FROM ",v_parameterSourceTable);
    PREPARE stmt FROM @v_query;
    EXECUTE stmt;

Docs