为什么这完美无缺:
SET @columnQuery = 'INSERT INTO ColumnNames SELECT ORDINAL_POSITION, COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME=''residents'' ORDER BY ORDINAL_POSITION;';
PREPARE STMT FROM @columnQuery;
EXECUTE STMT;
但这不是:
DECLARE TableName VARCHAR(50);
SET @TableName = 'residents';
SET @columnQuery = 'INSERT INTO ColumnNames SELECT ORDINAL_POSITION, COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME=''' + @TableName + ''' ORDER BY ORDINAL_POSITION;';
PREPARE STMT FROM @columnQuery;
EXECUTE STMT;
,这也不是:
DECLARE TableName VARCHAR(50);
SET @TableName = 'residents';
SET @columnQuery = CONCAT('INSERT INTO ColumnNames SELECT ORDINAL_POSITION, COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME=''', @TableName, ''' ORDER BY ORDINAL_POSITION;');
PREPARE STMT FROM @columnQuery;
EXECUTE STMT;
这两个都没有:
SET @columnQuery = 'INSERT INTO ColumnNames SELECT ORDINAL_POSITION, COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME=? ORDER BY ORDINAL_POSITION;';
PREPARE STMT FROM @columnQuery;
EXECUTE STMT USING @TableName;
以下是给我提出问题的一部分:
CREATE PROCEDURE sp_ReturnSingleRowAsXml
(
IN TableName VARCHAR(50)
)
BEGIN
DECLARE columnQuery VARCHAR(1000);
DROP TABLE IF EXISTS ColumnNames;
CREATE TEMPORARY TABLE ColumnNames (
ID INT, ColumnName VARCHAR(50)
);
SET @columnQuery = 'INSERT INTO ColumnNames SELECT ORDINAL_POSITION, COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME=''' + @TableName + ''' ORDER BY ORDINAL_POSITION;';
PREPARE STMT FROM @columnQuery;
EXECUTE STMT;
select * from ColumnNames;
END;
CALL sp_ReturnSingleRowAsXml('residents');
当select返回大约40行时,select不返回任何内容。但是,如果我在@columnQuery中硬编码“居民”这个词,我就会得到结果!是的,肯定有一张名为“居民”的桌子。
有时我会收到此错误,有时我不会,这取决于我是使用CONCAT还是只是手动连接字符串:
MySQL数据库错误:您的SQL语法出错;检查与MySQL服务器版本对应的手册,以便在第1行的“NULL”附近使用正确的语法
答案 0 :(得分:0)
试试这个:
DECLARE TableName VARCHAR(50);
SET @TableName = 'residents';
SET @columnQuery = 'INSERT INTO ColumnNames SELECT ORDINAL_POSITION, COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME=? ORDER BY ORDINAL_POSITION;';
PREPARE STMT FROM @columnQuery;
EXECUTE STMT USING @TableName;
答案 1 :(得分:0)
我能够使用以下内容:
CREATE PROCEDURE `sp_ReturnSingleRowAsXml`(
IN TableName VARCHAR(50)
)
BEGIN
DROP TABLE IF EXISTS ColumnNames;
CREATE TEMPORARY TABLE ColumnNames (
ID INT, ColumnName VARCHAR(50)
);
SET @tblName = TableName;
SET @columnQuery = 'INSERT INTO ColumnNames SELECT ORDINAL_POSITION, COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME=? ORDER BY ORDINAL_POSITION;';
PREPARE STMT FROM @columnQuery;
EXECUTE STMT USING @tblName;
select * from ColumnNames;
END