2014-02-18 29 views
0

任何人都可以幫助我調試這個存儲過程嗎?它完成了成功創建,但是當我在Navicat執行它,使用命令:MySQL存儲過程回聲「行受影響」,而不是所需的結果?

CALL getJoinTables('data2013q3', 2013, 2); 

雖然它產生了我PROC內創建視圖...

schema  table  alias 
data2013q3 b2013q2a a 
data2013q3 b2013q2b b 
master b2013q2t1 t1 
master b2013q2t2 t2 
master b2013q2t3 t3 

的Navicat返回一個消息聲明:

affected rows: -6 

當查詢應返回包含上述所有表的JOIN語句時。這裏是我的程序代碼:

CREATE PROCEDURE `common`.`getJoinTables`(IN strSchema varchar(35), IN iYr INT, IN iQtr INT) 
BEGIN 
DECLARE cursor_end CONDITION FOR SQLSTATE '02000'; 
DECLARE strPd, strTblPrefix, strBSearch, strMSearch VARCHAR(35); 
DECLARE strSqlJoinTables VARCHAR(500); 
DECLARE strTableSchema, strTable, strAlias VARCHAR(150); 
DECLARE done, i INT DEFAULT 0; 
DECLARE cur_tables CURSOR FOR SELECT strTableSchema, table_name, alias FROM common.vw_join_tables; 
DECLARE CONTINUE HANDLER FOR cursor_end SET done = 1; 

SET strPd = CONCAT(iYr, 'q', iQtr); 
SET strTblPrefix = CONCAT('b', strPd); 
SET strBSearch = CONCAT(strTblPrefix, '_'); 
SET strMSearch = CONCAT(strTblPrefix, 't_'); 
SET @strOut = ''; 
SET i=0; 

SET @strSqlJoinTables = CONCAT('CREATE VIEW common.vw_join_tables AS SELECT table_schema, table_name, REPLACE(table_name, \'', strTblPrefix, '\', \'\') alias 
FROM information_schema.TABLES 
WHERE (table_schema = \'master\' AND table_name LIKE \'', strMSearch, '\') OR (table_schema = \'', strSchema, '\' AND table_name LIKE \'', strBSearch, '\') 
GROUP BY table_schema, table_name 
ORDER BY table_schema, table_name'); 

DROP VIEW IF EXISTS common.vw_join_tables; 

SELECT @strSqlJoinTables; 
PREPARE stmt from @strSqlJoinTables; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 

OPEN cur_tables; 
FETCH cur_tables INTO strTableSchema, strTable, strAlias; 
read_loop: LOOP 
    IF done THEN 
     LEAVE read_loop; 
    END IF; 

    IF i = 0 THEN 
     SET @strOut = CONCAT(strTableSchema, '.', strTable, ' ', strAlias, ' '); 
    ELSE 
     SET @strOut = CONCAT(@strOut, ' JOIN ', strTableSchema, '.', strTable, ' ', strAlias, ' ON a.id=', strAlias, '.id '); 
    END IF; 

    SET i = i+1; 
    FETCH cur_tables INTO strTableSchema, strTable, strAlias; 
END LOOP; 

CLOSE cur_tables; 

SELECT @strOut; 
END 

回答

0

我想你想創建一個stored function而不是存儲過程。存儲的函數可以被定義爲返回一個字符串。

例如,你可以改變你的代碼是這樣的(我離開了大部分不改變的細節):

​​

然後,你可以這樣調用:

SELECT getJoinTables('data2013q3', 2013, 2); 
+0

你是絕對正確的,我想使用一個函數,但是,我動態生成SQL和使用準備好的語句,哪些(據我所知和閱讀)不允許在一個函數中。 – JLeRogue

+0

啊,是的,這是準確的。我沒有仔細觀察你的程序的正文。 –

相關問題