PL/PostgreSQL 如何将变量转换为表名

编程入门 行业动态 更新时间:2024-10-26 20:31:11
本文介绍了PL/PostgreSQL 如何将变量转换为表名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以我在 PostgreSQL 中有一个函数可以从动态表中动态选择列.我从 这篇文章,除了一件事之外,它的作用还不错.

So I have a function in PostgreSQL that dynamically selects columns from a dynamic table. I got this solution from this post and it works great other than one thing.

这是连接到节点服务器的文件内部,因此第二个 SELECT * FROM 中的 $1 和 $2 代表从那里传递的值.现在的问题是我收到了一个我不明白的语法错误(我对 SQL 比较陌生,所以这可能是原因).

This is inside of a file that is connected to a Node server, and so the $1 and $2 in the second SELECT * FROM represent values passed from there. The issue right now is that I am getting a syntax error that I don't understand (I am newer to SQL so that may be why).

$2 表示要从字符串中选择的表的名称,例如它可以是目标".该错误是目标"处或附近的语法错误.我意识到它不能是带单引号的字符串(我相信),所以我想知道如何将该变量转换为表名?使用目标"那里以及目标,例如按预期工作,但我不确定如何在函数之外做到这一点.

$2 represents the name of the table to be selected from as a string, so for example it could be 'goals'. The error is syntax error at or near "'goals'". I realize that it cannot be a string with single quotes (I believe) and so I am wondering how to convert that variable to be a table name? using "goals" there as well as goals, for example works as expected, though I'm not sure how to do that outside of a function.

CREATE OR REPLACE FUNCTION get_data(user_id INT, table_name anyelement) RETURNS SETOF ANYELEMENT AS $$ BEGIN RETURN QUERY EXECUTE format('SELECT * FROM %s WHERE user_id = $1', pg_typeof(table_name)) USING user_id; END; $$ LANGUAGE plpgsql; SELECT * FROM get_data($1, NULL::$2);

例如,$1 是 5,$2 是目标"

$1 is 5 and $2 is 'goals' for example

推荐答案

经过几个小时的尝试,多亏了 Adrian 的评论,我发现 MassiveJS(我如何连接到我的 PostgreSQL 服务器)有 内联函数进行查询.在我的服务器中的控制器文件中,我能够创建一个这样的单行函数:

After many hours of trying to figure it out, thanks to Adrian's comment, I found MassiveJS (how I'm connecting to my PostgreSQL server) has inline functions to do queries. In my controller file in my server I was able to create a one line function as such:

const data = await db[tableName].where("user_id=$1", [userId])

不知道 MassiveJS 中存在内联 SQL,所以发现它很棒!

Didn't know inline SQL existed in MassiveJS, so that was great to find out!

更多推荐

PL/PostgreSQL 如何将变量转换为表名

本文发布于:2023-07-20 22:12:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1171546.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   变量   如何将   PL   PostgreSQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!