下面是错误和存储过程,我有一个名为dropdown的表,它有两列像className和subject我想要做的是当我抛出任何这些列名时我需要获取该列数据。当我试图创建以下程序时出现错误
错误
(0 row(s) affected)
(0 ms taken)
Error Code : 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@result;
DECLARE @query;
SET @result = '';
SET @query = CONCAT('SELE' at line 8
(0 ms taken)
我的程序
DELIMITER $$;
DROP PROCEDURE IF EXISTS `testdb`.`getDropdown`$$
CREATE PROCEDURE `testdb`.`getDropdown` (in i_column_name varchar(250))
L_return:
BEGIN
DECLARE sqlstate_code CHAR(5) DEFAULT '00000';
DECLARE message_text TEXT;
DECLARE mysql_errno INT;
DECLARE status VARCHAR(10);
DECLARE @result;
DECLARE @query;
SET @result = '';
SET @query = CONCAT('SELECT ',in_columnName,' FROM test.dropdown');
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1
sqlstate_code = RETURNED_SQLSTATE,
mysql_errno = MYSQL_ERRNO,
message_text = MESSAGE_TEXT;
IF sqlstate_code <> '00000' THEN
SET @status = 'FATAL';
SELECT @status as status;
SELECT CONCAT(mysql_errno,': ',message_text) as ErrorMsg, 'Our System is down. We are working on it. Please come back in few minutes' as UserMsg;
END IF;
END;
PREPARE stmt FROM @query;
EXECUTE stmt using @result;
IF EXISTS(@result != '' OR @result IS NOT NULL)
THEN
SET @status = 'TRUE';
SELECT @status as status;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
LEAVE L_return;
ELSE
SET @status = 'FALSE';
SELECT @status as status;
SELECT CONCAT('No data in test.dropdown table')as ErrorMsg, CONCAT('Our System is down. We are working on it. Please come back in few minutes') as UserMsg;
LEAVE L_return;
END IF;
END$$
DELIMITER ;$$
答案 0 :(得分:0)
准备动态查询的示例。希望它对你有所帮助。
您需要做的就是准备并执行一份声明。
delimiter //
CREATE PROCEDURE dynamicQuery(IN TABLE_NAME VARCHAR(64), IN COL_NAME VARCHAR(64))
BEGIN
SET @q = CONCAT('SELECT ',COL_NAME,' FROM ',TABLE_NAME );
PREPARE stmt FROM @q;
EXECUTE stmt ;
DEALLOCATE PREPARE stmt;
END
//
delimiter ;
将它应用于您的代码,我没有采用整个SP。刚参加使用动态列的地方。
DECLARE @res;
DECLARE @q;
SET @res = '';
SET @q = CONCAT('SELECT ',in_columnName,' FROM test.dropdown');
PREPARE stmt FROM @q;
EXECUTE stmt using @res;
DEALLOCATE PREPARE stmt;
IF (@res != '' OR @res IS NOT NULL)
THEN
SET @status = 'TRUE';
SELECT @status as status;
END IF;