在Postgresql过程中创建并运行查询



我想创建一个postgresql过程,创建一个查询并运行它。我在论坛上进行了尝试和研究。但是我不能解决我的问题。过程应该将用户输入作为参数获取,并在查询中使用它。我的代码是这样的:


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);

这就是错误:

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是一个表。create语句:

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)
);

首先我创建了一个表格form_field(只需要两个字段来避免所有错误…(:

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

然后,我在您创建的函数中分析了您的查询,并意识到您选择了一个字符字段,而表form_field有两个字段。因此,我又创建了一个表:

create table return_test(return_col varchar(4000));

编辑了您的函数,而不是程序:

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

然后调用你的函数:

select * from myProcedure(2);

所以现在,你有了一些有效的东西。。。你可以编辑你的问题,也许这会帮助别人解决你原来的问题。。。

此外,请在问题的最后写下,当你向函数发送值2时,你希望函数应该执行什么?

这里有一个演示:

演示

最新更新