首页 > 解决方案 > 在 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"

编辑:form_field 是一个表。创建声明:

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

标签: sqlpostgresqlstored-procedures

解决方案


首先,我创建了一个表格 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 发送到该函数时,您希望该函数应该执行什么?

这是一个演示:

演示


推荐阅读