简体   繁体   中英

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 :

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 . 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:

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.

You can wrap the whole thing into a view (apparently without the WHERE condition) to make things easier.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM