我尝试在MySQL中构建某种通用序列化函数的原型,我希望在几个触发器中使用它来将表行的当前状态存储到另一个表中。
目标是具有数据的键值对的字符串,例如
id: 3; name: doe; surname: john; age: 25;
而键是表列的名称。
到目前为止,我提出了这个问题:
delimiter //
DROP PROCEDURE IF EXISTS SELECTOR //
CREATE PROCEDURE SELECTOR(
col_name varchar(255),
tbl_name varchar(255),
id integer,
out result text
)
BEGIN
set @q = CONCAT('SELECT ', col_name, ' FROM ', tbl_name, ' WHERE id = ', id );
PREPARE stmt FROM @q;
EXECUTE stmt;
DEALLOCATE PREPARe stmt;
END; //
DROP FUNCTION IF EXISTS SERIALISE //
CREATE FUNCTION SERIALISE(tbl VARCHAR(255), id integer) RETURNS text
BEGIN
DECLARE num_rows INTEGER;
DECLARE i INTEGER;
DECLARE col_name varchar(255);
DECLARE result varchar(255) DEFAULT "";
DECLARE value text;
DECLARE col_names CURSOR FOR
SELECT column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = tbl
ORDER BY ordinal_position;
open col_names;
SELECT FOUND_ROWS() INTO num_rows;
SET i = 1;
the_loop: LOOP
IF i > num_rows THEN
CLOSE col_names;
LEAVE the_loop;
END IF;
FETCH col_names
INTO col_name;
call SELECTOR(col_name, tbl, id, value);
// here the value would be concated as well
SET result = CONCAT(result, col_name, ", ");
SET i = i + 1;
END LOOP the_loop;
return result;
END; //
遗憾的是,函数或触发器中不允许使用动态SQL,因此SELECTOR过程不起作用。
是否有人提示如何实现我的目标,或者这是否真的不可能?