How to access customized object value inside postgresql function?

by raphael_tillman , in category: MySQL , 2 months ago

How to access customized object value inside postgresql function?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 2 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.