我的下表有两个字段:
create table tbl_jtest
(
cola int,
colb varchar(10)
);
插入一些记录:
insert into tbl_jtest values(1,'a');
insert into tbl_jtest values(2,'b');
insert into tbl_jtest values(3,'c');
insert into tbl_jtest values(4,'d');
功能:
CREATE OR REPLACE FUNCTION ufn_jtest1(pcola int)
RETURNS json AS
$$
BEGIN
IF pcola = 1
THEN
RETURN QUERY SELECT to_json(a.cola) FROM tbl_jtest a;
ELSE
RETURN QUERY SELECT to_json(a.colb) FROM tbl_jtest a;
END IF;
END;
$$ LANGUAGE plpgsql;
错误详情:
错误:无法在非SETOF功能LINE 7中使用RETURN QUERY: RETURN QUERY SELECT to_json(a.cola)FROM tbl_jtest a; ^
我尝试了以下内容:
尝试1 :
PERFORM to_json(a.cola) FROM tbl_jtest a;
尝试2 :
RETURN QUERY PERFORM to_json(a.cola) FROM tbl_jtest a;
答案 0 :(得分:3)
或者您正在寻找类似的东西吗?
create table tbl_jtest
(
cola int,
colb varchar(10),
colc varchar(10)
);
insert into tbl_jtest values(1,'a','e');
insert into tbl_jtest values(2,'b','f');
insert into tbl_jtest values(3,'c','g');
insert into tbl_jtest values(4,'d','h');
SELECT * FROM tbl_jtest;
CREATE OR REPLACE FUNCTION ufn_jtest1(pcola int)
RETURNS table (j json) AS
$$
BEGIN
IF pcola = 1
THEN
RETURN QUERY SELECT row_to_json(a) FROM (SELECT cola, colb FROM tbl_jtest) a;
ELSE
RETURN QUERY SELECT to_json(a) FROM (SELECT colb, colc FROM tbl_jtest) a;
END IF;
END;
$$ LANGUAGE plpgsql;
测试1
SELECT ufn_jtest1(1);
输出1
ufn_jtest1
1 {"cola":1,"colb":"a"}
2 {"cola":2,"colb":"b"}
3 {"cola":3,"colb":"c"}
4 {"cola":4,"colb":"d"}
的Test2
SELECT ufn_jtest1(2);
输出2 ufn_jtest1
1 {"colb":"a","colc":"e"}
2 {"colb":"b","colc":"f"}
3 {"colb":"c","colc":"g"}
4 {"colb":"d","colc":"h"}
答案 1 :(得分:1)
正在为这样做?:
CREATE OR REPLACE FUNCTION ufn_jtest2(pcola int)
RETURNS table (j json) AS
$$
BEGIN
IF pcola = 1
THEN
RETURN QUERY SELECT to_json(a.cola) FROM tbl_jtest a;
ELSE
RETURN QUERY SELECT to_json(a.colb) FROM tbl_jtest a;
END IF;
END;
$$ LANGUAGE plpgsql;