简体   繁体   English

数据库中的用户定义函数(PostgreSQL)

[英]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.

相关问题 将用户定义的逻辑存储在数据库中 - Storing user-defined logic in a database Oracle PIVOT子句中的用户定义聚合函数 - User-Defined Aggregate functions in Oracle PIVOT clause 在关系数据库中存储具有用户定义组件的实体 - Storing Entities with User-defined Components in Relational Database 数据库系统中用户定义的完整性规则示例? - Example of user-defined integrity rule in database systems? 支持用户定义的数据库字段的动态类 - Dynamic Class To Support User-Defined Database Fields 用户管理:以用户定义的“组”,数据库架构和物流管理用户 - User Management: Managing users in user-defined “groups”, database schema and logistics 您将如何设计数据库以允许用户定义的架构 - How would you design your database to allow user-defined schema 将用户定义的表类型与生成的数据库部署脚本一起使用时出现问题 - Problem using user-defined table type with generated database deployment script 您将如何在SQL数据库中创建和存储用户定义的自定义字段? - How would you create and store user-defined custom fields in a SQL database? 使用用户定义的函数搜索表 - Searching a table using a user-defined function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM