Skip to content
Advertisement

Create and Run Query in Postgresql Procedure

I want to create a postgresql procedure which creates a query and run it. I tried and research on forums. But i can not solve my problem. Procedure should get user input as a parameter and use it in query. My code like that :

create or replace function myProcedure(form_id int)
returns form_field as $$
(
*****I have to delete the code because of privacy. This part does not effect the problem.******
)
$$
language sql




call myProcedure(2);

And this is the error :

SQL Error [42P13]: ERROR: return type mismatch in function declared to return form_field
  Detail: Final statement returns text instead of integer at column 1.
  Where: SQL function "myProcedure"

edit: form_field is a table. create statement :

CREATE TABLE public.form_field (
    col1 int4 NOT NULL,
    id varchar(255) NULL,
    col2 bool NOT NULL,
    col3 jsonb NULL,
    "col4" varchar(255) NULL,
    col5 varchar(255) NULL,
    col6 int4 NULL,
    CONSTRAINT form_field_pkey PRIMARY KEY (field_id)
);

Advertisement

Answer

First I have created a table form_field(with only two fields I needed to avoid all errors…):

create table form_field(form_entity_id int, id varchar(20));

Then I have analized your query inside of the function you created and realized you are selecting one field of character and the table form_field has two fields. So, I have created one more table:

create table return_test(return_col varchar(4000));

Edited your function, not procedure:

create or replace function myProcedure(form_id int)
returns setof return_test  as $$
(
SELECT distinct 'create or replace view v_form'||form_entity_id||' as'||
' with t1 as ( SELECT *, form_values as jj FROM  form_instance where form_entity_id='||form_entity_id || ')'
FROM form_field  where form_entity_id=form_id
union all
select ' Select '
union all
SELECT E' jj->0->>'' || id || E''' || ' as ' || replace(replace(id,'/',''), '-','_') ||','
FROM form_field  where form_entity_id=form_id
union all
SELECT  column_name ||',' 
FROM information_schema.columns 
WHERE table_name='instance' and column_name!='values'
and ordinal_position!=(SELECT max(ordinal_position) FROM information_schema.columns where table_name='instance' ) 
union all
SELECT  column_name 
FROM information_schema.columns 
WHERE table_name='instance' --and column_name='values'
and ordinal_position=(SELECT max(ordinal_position) FROM information_schema.columns where table_name='instance' ) 
union all
select ' from t1 '
)
$$
language sql

And then called your function:

select * from myProcedure(2);

So now, you have something that works… you can edit your question and maybe this will help someone to resolve your original problem…

Also, please do write, at the end of your question, what your wish is the function should execute when you send value 2 to that function ?

Here is a demo:

DEMO

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement