mySQL 5.7 return row as json using new json features

こ雲淡風輕ζ 提交于 2019-12-05 09:53:37

Depends on what you mean by "name the keys or any kind of string manipulation". If you're happy to encapsulate said naming of keys and string manipulation inside a stored proc so that you don't need to name keys when you're calling the procedure, then yes, you can:

drop procedure if exists spGetJson;
delimiter $$
create procedure spGetJson(pTableName varchar(45), pId int)
begin

select  group_concat(concat("'", COLUMN_NAME, "', ", COLUMN_NAME) separator ',')
into    @cols
from    information_schema.columns
where   TABLE_NAME = pTableName and TABLE_SCHEMA = database();

set @q = concat('select json_object(', @cols, ') from ', pTableName);
if pId is not null then
    set @q = concat(@q, ' where id = ', pId);
end if;
set @q = concat(@q, ';');

prepare statement from @q;
execute statement;
deallocate prepare statement;

end $$
delimiter ;

You could then call this proc using either:

call spGetJson('people', 1);
call spGetJson('people', null);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!