我想知道如何从动态查询中获取字段值。我是在MySQL的存储过程中完成的。我有以下代码:
...
DECLARE l_query VARCHAR(500);
DECLARE l_table VARCHAR(50);
SET l_table = 'tb_user';
SET @l_query = concat('SELECT count(1) FROM ', l_table);
-- #Note that l_table will not always for tb_user,
-- it can be changed with other table name.
PREPARE l_sql FROM @l_query;
EXECUTE l_sql;
...
问题是,如何获得计数结果的值(count(1)
)..?我需要这个值,因为它将用于同一存储过程的下一个进程。
非常感谢。
答案 0 :(得分:1)
简短:使用SELECT INTO
选择变量值。
在你的情况下:
...
DECLARE l_query VARCHAR(500);
DECLARE l_table VARCHAR(50);
DECLARE cnt INTEGER;
SET l_table = 'tb_user';
SET @l_query = concat('SELECT count(1) INTO @cnt FROM ', l_table);
-- #Note that l_table will not always for tb_user,
-- it can be changed with other table name.
PREPARE l_sql FROM @l_query;
EXECUTE l_sql;
-- Use cnt variable here
...