2010-10-19 69 views
0

爲什麼這工作完美:MySQL的語法問題

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行。但是,如果我在@columnQuery中硬編碼「居民」這個詞,我會得到結果!是的,肯定有一張名爲「居民」的表。

有時候,我得到這個錯誤,有時我不知道,這取決於我是否使用CONCAT或只是手動連接字符串:

MySQL數據庫錯誤:你在你的SQL語法錯誤;檢查對應於你的MySQL服務器版本在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 
+0

太棒了!奇蹟般有效。那麼交易是什麼?輸入參數不能直接用於語句中?我必須先將它們放入局部變量中?奇怪的。 – Blackcoil 2010-10-19 18:00:42

0

使用近「NULL」正確的語法手冊試試這個:

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; 
+0

由於USING需要在EXECUTE之後才拋出錯誤。 – Blackcoil 2010-10-19 17:08:00

+0

我不好 - 我會更新。 – 2010-10-19 17:08:54

+0

它仍然無法正常工作。 :) – Blackcoil 2010-10-19 17:09:42