sql - Pass column name to a function -


create or replace function test123(column_name varchar(40)) returns record $$ declare        rec record ; begin     select * rec my_table column_name=1 limit 1;     return rec; end; $$ language plpgsql; 

how can pass column name function , use name in query?

the above code not work:

error: operator not exist: character varying = integer 

when want use function parameters identifiers in queries inside function need dynamically execute query:

create or replace function test123(column_name varchar(40)) returns record $$ declare        rec record; begin     execute format('select * my_table %i = 1 limit 1', column_name)     rec;     return rec; end; $$ language plpgsql; 

or shorter:

create or replace function test123(column_name varchar(40)) returns record $$ begin     return query execute format('select * my_table %i = 1 limit 1', column_name); end; $$ language plpgsql; 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -