[英]User-defined functions in Database (PostgreSQL)
Say I have defined the data-structure: 说我已经定义了数据结构:
Users(u_id, name);
As well as a stored-procedure / function to get a full profile of the user, given the u_id
: 以及给定u_id
的存储过程/函数,以获取用户的完整个人资料:
getUserProfile(u_id) RETURNS (u_id, firstname, lastname, age);
Now, I want to have a way to easily retrieve all users, say under the age of 20 . 现在,我希望有一种方法可以轻松地检索所有用户, 例如20岁以下 。 What would be the appropriate component to build on top of this, so that I could call something like: 在此之上构建合适的组件是什么,以便我可以这样称呼:
SELECT *
FROM user_profiles as UP
WHERE UP.age < '20'
Assuming getUserProfile() returns a custom data type with the mentioned columns, you can do the following: 假设getUserProfile()返回包含上述列的自定义数据类型,则可以执行以下操作:
SELECT (prof).u_id,
(prof).firstname,
(prof).lastname,
(prof).age
FROM (
SELECT getUserProfile(u_id) as prof
FROM users
) t
WHERE (prof).age < 20
Note that the column prof needs to be enclosed in brackets, otherwise the parser will think it's a table reference. 请注意, 列 prof需要用括号括起来,否则解析器将认为它是表引用。
You can wrap the whole thing into a view (apparently without the WHERE condition) to make things easier. 您可以将整个内容包装到一个视图中(显然没有WHERE条件),以使事情变得容易。
you need another stored-procedure / function to get the users under the age of 20 and for each user this first proc or function returns, you can call the second. 您需要另一个存储过程/函数来使20岁以下的用户使用,对于第一个proc或函数返回的每个用户,您可以调用第二个。
Or you can do everything in one structure. 或者,您可以在一个结构中完成所有工作。 Create a procedure that returns users' information and that accept another parameter called age and then you return a result set instead of only one user. 创建一个过程,该过程返回用户的信息并接受另一个称为age的参数,然后返回结果集,而不是仅返回一个用户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.