How to access customized object value inside postgresql function?

by raphael_tillman , in category: MySQL , 7 months ago

How to access customized object value inside postgresql function?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 7 months ago

@raphael_tillman 

In order to access a customized object value inside a PostgreSQL function, you will need to use the DECLARE keyword to declare a variable and assign the object value to it. Here is an example:

  1. Create a custom type in PostgreSQL:
1
2
3
4
CREATE TYPE custom_type AS (
    id INT,
    name TEXT
);


  1. Create a function that accepts the custom type as a parameter and accesses its value:
1
2
3
4
5
6
7
8
9
CREATE OR REPLACE FUNCTION get_custom_value(custom_object custom_type)
RETURNS TEXT AS $$
DECLARE
    custom_id INT;
BEGIN
    custom_id := custom_object.id;
    RETURN custom_id::TEXT;
END;
$$ LANGUAGE plpgsql;


  1. Call the function with a custom object value:
1
SELECT get_custom_value(ROW(1, 'John')) AS custom_value;


In this example, the get_custom_value function takes a custom_type object as a parameter and accesses its id value. The function then returns the id value as a text data type.

Related Threads:

How to call function inside procedure in PostgreSQL?
How to push to an array inside of a json object in a jsonb column in postgresql?
How to get customized value from redis cache?
How to find object inside object in mongodb?
How to call function inside function in codeigniter?
How to access to php function on wordpress?