对于MariaDB,这很容易,但对于PostgreSQL,这很棘手:
对于 MariaDB
您可以简单地编写如下程序:
CREATE PROCEDURE `test1`(IN tab_name VARCHAR(100),IN col_data_type VARCHAR(100))
BEGIN
select group_concat(column_name) into @x from information_schema.columns where table_name=tab_name and data_type=col_data_type;
SET @t1 =CONCAT("SELECT ", @x, " FROM ",tab_name);
PREPARE stmt3 FROM @t1;
EXECUTE stmt3;
DEALLOCATE PREPARE stmt3;
END
并像下面这样调用它:
call test1('test','varchar');
DEMO
对于 Postgresql:
您可以使用以下任何一种方法:
方法1.通过使用函数创建动态查询:如果你想在你的应用程序中运行它,那么你可以使用这种方法
一个。创建一个函数,它将根据表名和数据类型返回所需的查询,如下所示:
CREATE OR REPLACE FUNCTION get_query(schemaname VARCHAR,tabname VARCHAR, coltype VARCHAR) RETURNS TEXT
AS
$$
DECLARE
col_list text;
result text;
BEGIN
select
array_to_string(array_agg(quote_ident(column_name)),',')
from
information_schema.columns
where table_name=quote_ident(tabname)
and table_schema=quote_ident(schemaname)
and data_type=coltype into col_list;
return ('select '|| col_list ||' from ' || quote_ident(schemaname) ||'.'||quote_ident(tabname));
END;
$$
language plpgsql
b.然后调用上面的函数,它将以文本形式返回所需的查询,可以通过编程方式获取结果:
select * from get_query('public','test','integer');
-- Result : select * from get_query('public','test','integer');
DEMO
方法 2. 通过使用函数动态创建 TYPE 和 JSONB 结果:如果您只想在 DB 端运行它,那么此解决方法将为您做这些事情:
一个。根据表的结果集动态创建TYPE如下:
create or replace function create_type(schemaname varchar,tabname varchar, coltype varchar)
returns void as
$$
declare
col_list varchar;
begin
select
array_to_string(array_agg(quote_ident(column_name)||' '|| data_type),',')
from
information_schema.columns where table_name=quote_ident(tabname) and table_schema=quote_ident(schemaname) and data_type=coltype into col_list;
execute format('drop type if exists get_type;');
execute format('create type get_type as ('|| col_list ||')');
end;
$$
language plpgsql
b.现在创建一个函数,它将以JSONB 格式返回所需的结果:
create or replace function get_col(schemaname varchar,tabname varchar, coltype varchar) returns jsonb
as
$$
declare
col_list text;
x jsonb;
begin
select
array_to_string(array_agg(quote_ident(column_name)),',')
from
information_schema.columns where table_name=quote_ident(tabname) and table_schema=quote_ident(schemaname) and data_type=coltype into col_list;
execute format('select jsonb_agg(row_to_json(t1)) from (select '|| col_list ||' from test)t1') into x;
return x;
end;
$$
language plpgsql
- 调用这两个函数并使用
jsonb_populate_recordset将结果转换为表格形式:
select create_type('public','test','character varying');
select * from jsonb_populate_recordset(null::get_col1,
(select * from get_col('public','test','character varying')));
- 如果您负担得起 JSON 格式的结果以供编程使用,那么您可以简单地调用在第二步中创建的函数,该函数将返回所需记录的 JSON 数组。你可以这样称呼它:
select * from get_col('public','test','character varying');
DEMO