2012-07-30 64 views
0
DELIMITER $$ 

CREATE PROCEDURE `SearchUserX`(IN columnName VARCHAR(28) , IN search INT) 
BEGIN 
     DECLARE finished INT DEFAULT FALSE ; 
     DECLARE tableName VARCHAR (28) ; 
     DECLARE stmtFields TEXT ; 

    DECLARE tableNames CURSOR FOR 
       SELECT DISTINCT`TABLE_NAME` FROM `information_schema`.`COLUMNS` 
       WHERE `COLUMN_NAME` = columnName AND TABLE_SCHEMA = 'comments' ORDER BY `ORDINAL_POSITION` ; 
     DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = TRUE; 
     SET stmtFields = '' ; 
     OPEN tableNames; 
     readTables: LOOP 
       FETCH tableNames INTO tableName ; 
       IF finished THEN 
        LEAVE readTables ; 
       END IF; 
       SET stmtFields = CONCAT(
        stmtFields , IF (LENGTH(stmtFields) > 0 , ' AND' , '' ) , 
        ' `', tableName ,'`.`' , columnName , '`= ' , search ,'') ; 
     END LOOP; 
     SET @stmtQuery=CONCAT('SELECT * FROM `' , tableName , '` WHERE ' , stmtFields) ; 
     PREPARE stmt FROM @stmtQuery ; 
     EXECUTE stmt ; 
     CLOSE tableNames ; 
END 

我有錯誤可以有人幫助我:錯誤的程序

0 11:42:47 call SearchUserX('UserId',2) Error Code: 1054. Unknown column 'TabExample.UserId' in 'where clause' 

或我有在clausure語法問題stmtFields

+0

歡迎來到Stack Overflow。您可以使用工具欄按鈕格式化源代碼。這次我爲你做了。 – 2012-07-30 09:55:28

回答

0

的錯誤說:

未知列'Where子句'中的'TabExample.UserId'

您需要在表TabExample中添加第UserId列。

+0

但我有一個UserId列。我認爲它的問題與stmtFields – user1551590 2012-07-30 09:51:04

+0

試試這個和過去的輸出查詢在這裏。調用SearchUserX('UserId',2);選擇@stmtQuery; – Omesh 2012-07-30 09:52:56

+0

'SELECT * FROM'Newsweek1' WHERE'TabExample'.'UserId' = 2 AND'Newsweek1'.'UserId' = 2' 但是TabExample沒有一個值只有一列UserId。 – user1551590 2012-07-30 09:57:08