在postgres(plpgsql)中,如何制作一个在变量table_name上返回select *的函数?
基本上,至少为了概念证明,我想要一个可以运行的函数: SELECT res('表名');这会给我 SELECT * FROM table_name; 的结果。 我遇到的问题是模式......在我的函数声明中:
CREATE OR REPLACE FUNCTION res(table_name TEXT) RETURNS SETOF THISTHEPROBLEM AS
问题是我不知道如何声明我的返回,因为它想要我指定一个表或一个模式,在函数实际运行之前我不会得到它。
有什么想法吗?
Basically, at least for proof of concept, I want a function where I can run:
SELECT res('table_name'); and this will give me the results of SELECT * FROM table_name;.
The issue I am having is schema...in the declaration of the function I have:
CREATE OR REPLACE FUNCTION res(table_name TEXT) RETURNS SETOF THISISTHEPROBLEM AS
The problem is that I do not know how to declare my return, as it wants me to specify a table or a schema, and I won't have that until the function is actually run.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以执行此操作,但如前所述,您必须在
SELECT
查询中添加列定义列表。You can do this, but as mentioned before you have to add a column definiton list in the
SELECT
query.为什么出于任何真正的实际目的,您只想传入表并从中选择 * ?也许是为了好玩?
如果不定义某种已知的输出(例如 jack 和 rudi show),您就无法做到这一点。或者像 depesz 在这里使用输出参数那样 http://www.depesz.com/index.php/2008/05/03/waiting-for-84-return-query-execute-and-cursor_tuple_fraction/。
一些绕墙方法是循环发出引发通知并一次一行打印结果集。或者您可以创建一个名为 get_rows_TABLENAME 的函数,其中包含您要返回的每个表的定义。只需使用代码来生成过程创建。但再次不确定从表中执行 select * 有多大价值,尤其是在没有约束的情况下,除了为了好玩或让 DBA 热血沸腾之外。
现在,在 SQL Server 中,您可以让存储过程返回动态结果集。这既是一种祝福也是一种诅咒,因为如果不查找定义就无法确定返回的结果是什么。对我来说,我认为 PostgreSQL 的实现是更合理的方法。
Why for any real practical purpose would you just want to pass in table and select * from it? For fun maybe?
You can't do it without defining some kind of known output like jack and rudi show. Or doing it like depesz does here using output parameters http://www.depesz.com/index.php/2008/05/03/waiting-for-84-return-query-execute-and-cursor_tuple_fraction/.
A few hack around the wall approachs are to issue raise notices in a loop and print out a result set one row at a time. Or you could create a function called get_rows_TABLENAME that has a definition for every table you want to return. Just use code to generate the procedures creations. But again not sure how much value doing a select * from a table, especially with no constraints is other than for fun or making the DBA's blood boil.
Now in SQL Server you can have a stored procedure return a dynamic result set. This is both a blessing and curse as you can't be certain what comes back without looking up the definition. For me I look at PostgreSQL's implementation to be the more sound way to go about it.
即使您设法做到这一点(如果您有 8.4 或更高版本,请参阅 rudi-moore 的答案),您也必须在
select
中显式扩展类型 - 例如:Even if you manage to do this (see rudi-moore's answer for a way if you have 8.4 or above), You will have to expand the type explicitly in the
select
- eg: