I want fetch data from different different table name using postgresql function

故事扮演 提交于 2019-12-18 09:53:16

问题


I have 30 state wise data tables. Table name like aa_shg_detail, ab_shg_detail, ac_shg_detail.

I have also main state table in which state short names and state codes are stored. I have created 2 postgresql functions getTableName(Code text) and getDataByTable().

In the first function I pass the state code so it fetches the state short name and short name concat with _shg_detail String and prepare full table name and return it. Example: If I pass state code 2 the query fetch state short name based on state code 2 from the state's main table. The state short name is 'ab' for state code 2 so after concat state short name with _shg_detail first function return ab_shg_detail table name.

Second function gets the table name from first function and fetch data from that table. But I am getting error in the second function.

CREATE OR REPLACE FUNCTION getTableName(code text) 
  RETURNS text 
AS $$ 
   select concat(lower(state_short_name), '_shg_detail') from main_state where state_code = code)) 
$$  
LANGUAGE sql; 

CREATE OR REPLACE FUNCTION getDataByTable() 
  RETURNS text AS $$ 
DECLARE 
    tablename text; 
BEGIN 
   tablename := gettablename('2');
   RETURN (select shg_code from tablename);  
END;
$$  LANGUAGE plpgsql; 

When I execute a second function select getDataByTable() then I am getting this error every time:

ERROR:  relation "tablename" does not exist
LINE 1: SELECT (select shg_code from tableName)

回答1:


You need dynamic SQL for that:

CREATE OR REPLACE FUNCTION getDataByTable() 
  RETURNS text AS $$ 
DECLARE 
    tablename text;
    l_result text; 
BEGIN 
   tablename := gettablename('2');
   execute format('select shg_code from %I', tablename)  
     into l_result;
   RETURN l_result;  
END;
$$  LANGUAGE plpgsql; 

The %I placeholder of the format() function properly deals with quoting of identifiers if needed.



来源:https://stackoverflow.com/questions/57671148/i-want-fetch-data-from-different-different-table-name-using-postgresql-function

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