How do I write a postgres stored procedure that doesn't return anything?

£可爱£侵袭症+ 提交于 2019-12-08 16:22:37

问题


How do I write a simple stored procedure in postgres that doesn't return a value at all? Even with a void return type when I call the stored procedure I get a single row back.

CREATE FUNCTION somefunc(in_id bigint) RETURNS void AS $$
BEGIN
   DELETE from test_table where id = in_id;
END;
$$ LANGUAGE plpgsql;

回答1:


It's not the function that returns value, it's the SELECT you used to call it. If it doesn't return any rows, it doesn't run your function.




回答2:


You can achieve "nothing returned" by abusing set-returning functions:

Simple function:

create function x () returns setof record as $$
begin
return;
END;
$$ language plpgsql;

Now you can:

# select x();
 x
---
(0 rows)

In case it doesn't work for you (sorry, I'm using 8.5), try with this approach:

# create function x (OUT o1 bool, OUT o2 bool) returns setof record as $$
begin
return;
END;
$$ language plpgsql;
CREATE FUNCTION

The parameters are irrelevant, but:

  • You need > 1 of them
  • They have to be named

And now you can:

# select * from x();
 o1 | o2
----+----
(0 rows)



回答3:


You are doing just fine. You dont need to add anything else.

The result of the row is null, so it is a void return.

I don't think theres something you can do about that. Checking my void functions all of them are just like yours.

returns void as $$ and no return statement in code block.



来源:https://stackoverflow.com/questions/1343954/how-do-i-write-a-postgres-stored-procedure-that-doesnt-return-anything

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!