在程序

时间:2017-01-10 16:58:32

标签: mysql stored-procedures information-schema

我成功运行了一个查询,选择了information_schema中表的列名,但是如果我在存储过程中运行相同的查询以将其与游标一起使用,那么information_schema是未知的。谁能告诉我原因并帮助我解决问题?谢谢 这是查询

 SELECT column_name
FROM information_schema.columns
WHERE table_schema = 'database_name'
AND table_name='Table_name';

这是程序。

    DELIMITER $$

    CREATE PROCEDURE build_column_names_str (INOUT column_list varchar(4000))
    BEGIN

     DECLARE v_finished INTEGER DEFAULT 0;
            DECLARE v_column varchar(100) DEFAULT "";

    -- declare cursor for column names
    DEClARE column_cursor CURSOR FOR 
     SELECT column_name
        FROM information_schema.columns
        WHERE table_schema = 'database_name'
        AND table_name='Table_name';

    -- declare NOT FOUND handler
    DECLARE CONTINUE HANDLER 
    FOR NOT FOUND SET v_finished = 1;

     OPEN column_cursor;

     get_column: LOOP

     FETCH column_cursor INTO v_column;

     IF v_finished = 1 THEN 
     LEAVE get_column;
     END IF;

     -- build column name list
     SET column_list = CONCAT(v_column,",",column_list);

     END LOOP get_column;

     CLOSE column_cursor;

    END$$

    DELIMITER ;

    SET @column_list = "";
    CALL build_column_names_str(@column_list);
    SELECT @column_list;

由于

2 个答案:

答案 0 :(得分:1)

您的代码是正确的。

检查程序执行的权限
或用

替换程序
SELECT airportname, COUNT(DISTINCT foundBag.id) countFound, COUNT(DISTINCT lostBag.id) countLost 
FROM airports 
INNER JOIN foundBag ON airport_id = foundBag.airportDest 
INNER JOIN lostBag ON airport_id = lostBag.airportDest 
GROUP BY airport.airportname");

答案 1 :(得分:0)

我对information_schema.tables也有类似的问题:当我在存储过程中调用information_schema.tables时,它为所有字段返回NULL,并且更奇怪的是,存储过程中的另一个表又从另一个表中进行选择还会为每个字段返回NULL。

我通过在WHERE TABLE_SCHEMA = DATABASE()的SELECT中添加information_schema.tables来解决了这个问题